2016-02-17 71 views
1

问题为什么这个onClick事件不能在HTML iframe中工作?

我想在用户点击iframe时使用onClick事件进行注册。为什么这不起作用?

这里是一个fiddle

代码

<html> 
<head> 
<script> 

function myFunction() { 
    document.getElementById("demo").innerHTML = "Hello World"; 
} 
</script> 
</head> 

<body onLoad="def()"> 
<iframe id="myFrame" border="0" onclick="myFunction()"></iframe> 
<p id="demo"></p> 

</body> 
</html> 
+1

点击事件只会触发iframe的边框不是里面 – RRR

+0

你将不得不监听器绑定到页面的iframe内。 (我相信有这一个易受骗的人) – epascarello

+0

我不能到里面页面上添加一个监听器,因为它链接到另一个网站。无论如何,我可以检测到有人点击iframe而没有用范围之类的东西来掩盖iframe? –

回答

1

如果iframe是从您自己的网站,你可以这样写:

document.getElementById("myFrame") 
    .contentWindow.document.body 
    .onclick = function() { 
     alert("iframe clicked"); 
    } 

代码但不若工作iframe来自不同于主机页面的域。

+0

不幸的是我没有任何主机或自己加载的页面是不可能的iframe中捕获它的页面必须从iframe标签的相同页面完成。 –

+0

我需要这样的事,但对于具有不同ID的多个iframe http://jsfiddle.net/oqjgzsm0/ –

0

我不知道这是否与工作不CORS或任何网站,但我需要这个曾与多个iframe具有不同ID的 - 当你点击 https://jsfiddle.net/ab0a/1fyoajqc/6/

<!-- Multiple iframes with different IDs --> 
<iframe id="iframe" src="https://livestream.com/accounts/5690925/events/6124324/player?width=960&height=540&enableInfoAndActivity=true&defaultDrawer=feed&autoPlay=true&mute=false" width="960" height="540" frameborder="0" scrolling="no" allowfullscreen></iframe> 
<iframe id="iframetwo" src="iframe/here/too" width="960" height="540" frameborder="0" scrolling="no" allowfullscreen></iframe> 
<iframe id="iframethree" src="iframe/here/as/well" width="960" height="540" frameborder="0" scrolling="no" allowfullscreen></iframe> 
<div id="message"></div> 

<script> 
var monitor = setInterval(function() { 
    var elem = document.activeElement; 
    if (elem.id == 'iframe') { 
    message.innerHTML = 'One'; 
    //use clearInterval(monitor); if you want to stop checking 
    //clearInterval(monitor); 
    } 
    if (elem.id == 'iframetwo') { 
    message.innerHTML = 'Two'; 
    //clearInterval(monitor); 
    } 
}, 100); 

/* If you only want to check for a specific iframe once, but still want to check for others, set up another monitor for that specific iframe */ 
var monitorTwo = setInterval(function() { 
    var elemTwo = document.activeElement; 
    if (elemTwo.id == 'iframethree') { 
    message.innerHTML = 'Three'; 
    message.style = 'background-color: red;'; 
    clearInterval(monitorTwo); 
    } 
}) 
</script> 
相关问题