<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 位于同一域中,它就应该可以工作。
关于如何实现这项工作有什么想法吗?
最佳答案
最终编辑:
有两个问题:
使用
$('#source').contents()
而不是简单地使用$('#source')
.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/