<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位于同一个域上,就应该有效。
关于如何使这项工作的任何想法?
答案 0 :(得分:6)
有两个问题:
使用$('#source').contents()
而不是简单地使用$('#source')
在iframe的上下文中,.hover
的css规则不可见
可以使用.css()
直接设置样式,在demo.php
中添加css链接,或者使用jQuery将主文档中的所有样式克隆到iframe中。
另外你应该避免使用.live
,因为iframe中似乎有some issue个(当使用实时jQuery时会绑定文档上的特殊eventHandlers,并在事件冒出时检查事件)
以下是一个工作示例(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。
好的,所以实际问题是在iframe中看不到css样式。
例如,如果您使用$(this).css('color':'red')
代替addClass
,则可以使用。请参阅更新的jsFiddle
我建议要么在demo.php
中有正确的css样式,要么在之后插入如下:
$('head',doc).append($('style, link[rel=stylesheet]').clone());
updated jsFiddle - 使用addClass和克隆样式
答案 1 :(得分:0)
尝试使用此contents:
demo.php:
<html>
<head>
...
</head>
<body>
<div id="container-div">
...
</div>
</body>
</html>
代码:
<iframe src="/demo.php" id="source"></iframe>
$('#source').contents().delegate('container-div', 'hover', function() {
$(this).addClass('hover');
});
$('#source').contents().delegate('container-div', 'mouseout', function() {
$(this).removeClass('hover');
});
$('#source').contents().delegate('container-div', 'click', function() {
alert($(this).html());
return false;
});