Capturing of keydown events in a html page with frames

那年仲夏 提交于 2019-12-01 11:17:18
Marcus Whybrow

Remember a frame is a completely new HTML page with a whole separate DOM, so jQuery doesn't include it in your bindings.

So you will need to bind to those documents also:

function keyDownHandler(e) {
    if(e.keyCode==27){
        alert("escape pressed");
        e.preventDefault();
    }
}

for (var id in window.parent.frames)
    $(window.parent.frames[id].document).keydown(keyDownHandler);
$(document).keydown(keyDownHandler);

If the above doesn't work for you because of the id:

for (var i = 0; i < window.parent.frames.length; i ++) {
   var frame = window.parent.frames[i].document;
   frame.addEventListener("keydown",keyDownHandler, true);
}

If you want to reference all frames, from the top level

for (var i = 0; i < top.window.frames.length; i ++) {
   var frame = top.window.frames[i].document;
   frame.addEventListener("keydown",keyDownHandler, true);
}

You can also try this:

Write your code in .js file and include file in all frames. This way you have to write function only onces and you can call it in all frames.

Hope this hepls.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!