【发布时间】:2018-06-05 05:54:29
【问题描述】:
我想为 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>
【问题讨论】:
-
好的,您在 iframe 内的页面上有编辑权限吗?
标签: javascript jquery iframe jquery-on