iframe之键盘事件监听

iframe之键盘事件监听

场景:

子页面中如果聚焦,页面会监听子页面的键盘事件,监听不到父页面和其他子页面的键盘事件

原理:

在父级别页面,获取到子页面的window,挂载监听事件

代码:

<html>
<body>
    <iframe id="if2" src="2.html" frameborder="0"></iframe>
    <iframe id="if3" src="3.html" frameborder="0"></iframe>
</body>
<script>
    function qEvent(){
        console.log('q')
    }
    window.onkeydown = function (e) {
        if(e.key=='q'){
            qEvent()
        }
    }
    let if2 = document.getElementById("if2").contentWindow
    console.log(if2)
    if2.onkeydown = function (e) {
        if(e.key=='q'){
            qEvent()
        }
    }
    let if3 = document.getElementById("if3").contentWindow
    console.log(if2)
    if3.onkeydown = function (e) {
        if(e.key=='q'){
            qEvent()
        }
    }
</script>
</html>

 

 

 

 

 

钻研不易,转载请注明出处。。。。。。

 

posted @ 2022-06-14 10:40  莫小龙  阅读(1930)  评论(0编辑  收藏  举报