简体   繁体   English

防止iframe使用jquery保持焦点

[英]Prevent iframe from keeping focus using jquery

Background: 背景:

I'm helping an old friend who has a mixed media slideshow, and one of the slides is an iframe embed of a lytro camera image (it's interactive and you can click or tap on mobile to change the focus). 我正在帮助一个有混合媒体幻灯片放映的老朋友,幻灯片中的一张是嵌入了lytro相机图像的iframe(它是交互式的,您可以单击或点击移动设备来更改焦点)。

Issue: 问题:

The issue that I'm having is that when you interact with the iframe, it steals keyboard focus on desktops and that prevents the arrow keys from allowing you to change slides. 我遇到的问题是,当您与iframe进行交互时,它会将键盘的焦点移到台式机上,并且阻止了箭头键允许您更改幻灯片。

What I've tried: 我尝试过的

My main attack angle on this had been trying to use jquery to set a timer that periodically sets focus on the parent document, to remove focus from the iframe and allow the keystrokes to be captured properly. 我对此的主要攻击角度是试图使用jquery设置一个计时器,该计时器定期将焦点设置在父文档上,以从iframe中移除焦点并允许正确捕获击键。 I've noticed that if I click anywhere outside of the iframe then I can use the arrow keys properly. 我注意到,如果单击iframe以外的任何位置,则可以正确使用箭头键。

Here's my jquery code, along with comments about why I tried each method. 这是我的jquery代码,以及有关为什么尝试每种方法的注释。 Unfortunatly nothing has worked (I've also tried including the lytro image with an embed tag instead of the iframe tag with no change in results). 不幸的是,没有任何效果(我也尝试过将带有embed标签而不是iframe标签的lytro图像包括在内,结果保持不变)。

<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>

Your issue seems to be two-fold. 您的问题似乎有两个方面。

  1. You are using setTimeout which will only run your callback once. 您正在使用setTimeout ,它将仅运行一次回调。 I think you mean to use setInterval , which will repeatedly run the callback. 我认为您的意思是使用setInterval ,它将重复运行回调。

  2. You can't set focus to document using the focus method natively or in jQuery. 您不能在本地或jQuery中使用focus方法将focus设置为document In order to restore focus to the body , you should call the blur method on the currently active element using document.activeElement . 为了将焦点恢复到body ,应使用document.activeElement在当前活动元素上调用blur方法。

Example: 例:

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

CodePen Demo CodePen演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM