我想为iframe添加mousemove和keypress事件。以下代码适用于页面中现有的iframe,但不适用于通过javascript在文档中动态创建的框架。
$('iframe').contents().keypress(function(){
console.log('iframe keypress event fired1');
});
$('iframe').contents().mousemove(function(){
console.log('iframe mousemove event fired2');
});我想让这个工作后,动态创建的框架加载的文件。我已经复制了下面的全部代码。
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Iframe Events Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div>Existing Iframe</div>
<input id="btnFrame" type="button" value="Load Dynamic Iframe"/>
<iframe width="200px" height="100px"></iframe>
</body>
<script>
$(document).ready(function() {
console.log('document ready event...');
$('#btnFrame').click(function(){
console.log('btn click event...');
console.log($('iframe#dynamic').length);
if ($('iframe#dynamic').length === 0) {
prepareFrame();
}
});
});
$(window).on('load', function() {
$('iframe').on("load", function () {
// All the contents of the iframe are loaded
$('iframe').contents().keypress(function(){
console.log('iframe keypress event fired');
});
});
});
function prepareFrame() {
var ifrm = document.createElement("iframe");
ifrm.setAttribute("id", 'dynamic');
ifrm.style.width = "640px";
ifrm.style.height = "480px";
document.body.appendChild(ifrm);
}
</script>
</html>发布于 2018-06-05 14:08:01
这是因为当您注册事件侦听器时,您的iframe不可用。您可以在视图加载完成后注册事件侦听器。
$(window).on('load', function() {
$('iframe').on("load", function () {
// All the contents of the iframe are loaded
$('iframe').contents().keypress(function(){
console.log('iframe keypress event fired');
});
});
});发布于 2021-12-29 09:01:15
使用Iframe的JS First get元素获取点击事件的更好方法
const iframe = document.getElementsByTagName('iframe')[0];然后在HTML中添加一个Id为'play_video‘的锚定标签,并添加点击事件
const play = document.getElementById('play_video');
play.click();这就是你将如何得到一个事件点击的Iframe,这是动态加载从CMS或数据库。
https://stackoverflow.com/questions/50692922
复制相似问题