使用jquery阻止iframe保持焦点

时间:2014-09-08 01:02:46

标签: javascript jquery iframe focus embed

背景

我正在帮助一位拥有混合媒体幻灯片的老朋友,其中一张幻灯片是嵌入了lytro相机图片的iframe(它是互动式的,您可以点击或点按手机进行更改重点)。

问题:

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

我尝试过的事情:

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

这是我的jquery代码,以及有关我尝试每种方法的原因的评论。遗憾的是没有任何效果(我还尝试将lytro图像包含在embed标签中,而不是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 个答案:

答案 0 :(得分:1)

您的问题似乎有两方面。

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

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

  3. 示例:

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

    <强> CodePen Demo