防止iframe使用jquery保持焦点

Prevent iframe from keeping focus using jquery

本文关键字:焦点 jquery iframe 使用 防止      更新时间:2023-09-26

背景:

我正在帮助一位老朋友,他有一个混合媒体幻灯片,其中一张幻灯片是嵌入lytro相机图像的iframe(它是交互式的,你可以点击或点击手机来更改焦点)。

问题:

我遇到的问题是,当你与iframe交互时,它会窃取桌面上的键盘焦点,并阻止箭头键允许你更改幻灯片。

我尝试过的:

我对此的主要攻击角度是试图使用jquery设置一个计时器,定期将焦点设置在父文档上,从iframe中删除焦点,并允许正确捕获击键。我注意到,如果我点击iframe之外的任何地方,那么我就可以正确地使用箭头键。

以下是我的jquery代码,以及关于我为什么尝试每种方法的注释。不幸的是,什么都没有起作用(我还尝试将lytro图像包含在嵌入标签中,而不是结果不变的iframe标签中)。

<script>
    //make sure body maintains focus, so that swipe and arrows still work
    function focusit(){
        $('#focushere').focus(); // this is a div on the main page that I tried to set focus to
        $('body').focus(); // tried moving focus to the body
        $('embed').blur(); // tried bluring the embed
        $('iframe').blur(); // tried bluring the iframe
        $('body').click(); // tried faking a click on the body 
        $('#focushere').click(); //tried faking a click on a element 
        $(document).click(); // tried click on document
        $(document).focus(); //tried setting focus to document
    }
    setTimeout(focusit, 100);
</script>

您的问题似乎有两个方面。

  1. 您使用的是setTimeout,它只会运行一次回调。我认为您的意思是使用setInterval,它将重复运行回调。

  2. 不能在本机或jQuery中使用focus方法将焦点设置为document。为了将焦点恢复到body,您应该使用document.activeElement对当前活动元素调用blur方法。

示例:

function focusit(){
    if(document.activeElement)
    {
        document.activeElement.blur();
    }
}
setInterval(focusit, 100);

CodePen演示