jquery - 使用 jQuery 将类添加到 iframe 中的元素

标签 jquery iframe

<iframe src="/demo.php" id="source"></iframe>

$('#source').delegate('*', 'hover', function() {
    $(this).addClass('hover');  
});

$('#source').delegate('*', 'mouseout', function() {
    $(this).removeClass('hover');   
});

$('#source').delegate('*', 'click', function() {
    alert($(this).html());
    return false;
});

当我将鼠标悬停或单击 Iframe 内的任何元素时,没有任何反应。 Iframe 位于同一域中,我曾经/现在的印象是,只要 Iframe src 位于同一域中,它就应该可以工作。

关于如何实现这项工作有什么想法吗?

最佳答案

最终编辑:

有两个问题:

  1. 使用 $('#source').contents() 而不是简单地使用 $('#source')

  2. .hover 的 CSS 规则在 iframe 上下文中不可见。
    可以直接使用 .css() 设置样式,在 demo.php 中添加 css 链接,或者使用 jQuery 将主文档中的所有样式克隆到 iframe 中。

此外,您应该避免 .live 因为似乎有 some issue iframe 内(当使用实时 jQuery 时,会在文档上绑定(bind)特殊的事件处理程序,并在事件冒泡时检查事件)

这是一个工作示例( jsFiddle link ):

var $c = $('#source').contents();

//clone all styles from this document into the iframe
$c.find('head').append($('style, link[rel=stylesheet]').clone());

$c.find('body').prepend('<b>This is a test</b><br><b>Click here</b>');

$c.delegate('b', 'hover', function() {
    $(this).toggleClass('hover');
});

$c.delegate('b', 'click', function() {
    alert('You clicked on:' + $(this).text());
});
<小时/>

原始答案:

您的问题是您正在使用 iframe 作为上下文。您应该使用框架文档。

另外,为了安全起见,您可能需要在 onload 事件中添加代码,如下所示:

var doc = window.frames['source'].document;
$(doc).ready(function(){
    $('body').prepend('This is outside the iframe<br>');
    $('body',doc).prepend('This is inside the iframe<br>');
});

您可以查看此live jsFiddle example .

<小时/>

编辑1:

好的,所以实际的问题是 css 样式在 iframe 中不可见。

例如,如果您使用 $(this).css('color':'red') 而不是 addClass ,它就会起作用。查看更新后的 jsFiddle

我的建议是要么在 demo.php 中拥有正确的 css 样式,要么像这样在之后插入:

$('head',doc).append($('style, link[rel=stylesheet]').clone());

updated jsFiddle - 使用 addClass 和样式克隆

关于jquery - 使用 jQuery 将类添加到 iframe 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3991146/

相关文章:

javascript - Facebook 页脚栏是一个 iframe,那么为什么它不与页面的其余部分一起重新加载呢?

javascript - 如何从 iframe 调用函数

javascript - 单选按钮选中的属性未设置为 false

javascript - CKEditor 5 弹出控件在 Bootstrap 3 - 2018 中不起作用

javascript - jQuery 在输入检查时增加/减少值

javascript - "Friendly iFrame"检测 : How can I find my nested iframe in the top page?

javascript - 从父级中的播放按钮在 iframe 内播放 html5 视频

javascript - 首次检索 Iframe 数据时出现问题

jQuery 选择器无法正常工作

javascript - 在 ember.js 路由中按属性过滤多个模型