我正在开发一个网站,当用户在文本框中输入内容时,该网站会加载一个 iframe(来自另一个域)。
有时,iframe 加载的网站会抢走焦点。这尤其烦人,因为用户一直在我的 文本框中输入,现在将输入到iframe 的 文本框中。
似乎没有办法阻止 iframe 窃取焦点。为了缓解这种情况,我试图想出一种明智的方法来确定何时重新聚焦我的文本区域。原来是挺头疼的。 这很糟糕的主要原因是因为我无法找到一种方法来判断我的文本框何时被故意模糊,以及 iframe 何时窃取了焦点。
这是我目前所了解的,但我需要一些帮助:
var my_textbox = $("#my_textbox");
var iframe = $("#iframe");
var enableBlur = true;
my_textbox.blur(function(){
if (!enableBlur){
//settimeout is required to redo focus. annoying.
//sadly, within these "0" ms, the user can still type
//into the iframe's textbox. like i said: annoying. :(
setTimeout(function(){ my_textbox[0].focus(); } , 0);
}
});
//later on, in some function
//lets disable blur while the iframe loads
enableBlur = false;
iframe.attr("src", "http://www.some-site-that-steals-focus.com");
iframe.bind("load", function(){
//note: this is fired *after* the page loads
//assume the threat of focus stealing is gone
//after 1 second of the iframe being loaded
setTimeout(function(){ enableBlur = true; }, 1000);
});
现在请注意,如果您想有意停止在文本字段中键入内容,这将是多么糟糕的用户体验。在加载 iframe 时,您被“锁定”在文本字段中……您甚至无法在浏览器的地址栏中输入内容。
关于如何改进这个的任何想法?我希望我错过了一些完全明显的东西,但我很确定我没有。
一如既往,感谢您的帮助。
最佳答案
一些想法(仅此而已)
观察文档的onmouseout-Event,比较坐标和iframe的坐标。 所以应该有可能发现用户是否进入了 iframe(并且你可以假设一个“好的”焦点)
当然还有更多方法可以将焦点设置到iframe,例如使用[TAB]导航
要捕获这一点,您可以在 iframe 之前插入一个可以立即获得焦点的元素。 它应该在 iframe 之前获得焦点。
关于javascript - 如何防止 iFrame 窃取焦点 [高级]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3844232/