我遇到的问题,后台是通过创建iframe窗口来添加页面显示的,公共页需要编写公共的事件,用正常的jquery的绑定事件无法获取到iframe内的DOM
获取iframe中内容主要的两个API就是contentWindow
,和contentDocument iframe.contentWindow
, 获取iframe的window对象 iframe.contentDocument
, 获取iframe的document对象 这两个API只是DOM节点提供的方式
后台多个iframe动态创建的窗口
写的监听如下:
我这里使用的是标签 document.getElementsByTagName("iframe") 是因为有多个iframe
如果只有一个就不用for循环遍历了,
只有一个完全可以使用 document.getElementById('id');
$(document).ready(function(){
eachIframe();
function eachIframe() {
setTimeout(function(params) {
var iframe = document.getElementsByTagName("iframe");
for(var i=0;i <iframe.length;i++){
iframe1 = iframe[i];
var iwindow = iframe1.contentWindow;
var idoc = iwindow.document;
//console.log("window",iwindow);//获取iframe的window对象
//console.log("document",idoc); //获取iframe的document
//console.log("html",idoc.documentElement);//获取iframe的html
//console.log("head",idoc.head); //获取head
//console.log("body",idoc.body); //获取body
//监听keydown事件
$(idoc.documentElement).on('keydown',function (e) {
if (e.keyCode === 82 && window.event.altKey) {
// console.log("你按下了alt+R");
if($(".search_menu_block").is(":hidden")){
//show
}else{
//hide
}
}
});
//监听click事件
$(idoc.documentElement).on("click",".layui-btn.layui-btn-mini.pj_btn,.layui-btn.layui-btn-small.pj_btn",function(params) {
//监听iframe里的button
eachIframe();
})
}
},1500);
}
})