我使用keydown事件将一些键盘快捷键绑定到文档对象(我使用jquery.hotkeys插件执行此操作,但我怀疑这很重要。)
然后我有一个iframe,我动态插入到DOM中,并在一些操作后将其删除。我的问题是,在删除iframe后,我需要单击父文档以便能够使用键盘快捷键,否则不会检测到keydown事件。
我尝试在文档元素上以及父页面上的其他元素上使用.focus(),. click(),. mousedown()等,但我无法将焦点重新放回到父页面。
如何在不要求用户点击页面的情况下将焦点重新放回页面? 谢谢!
答案 0 :(得分:0)
如果你有一个文件中包含的iframe,你可以在创建iframe之前将“main”文档存储为变量。
然后当你删除iframe时,只需调用top.doc.focus()或top.doc.getElement('id')。focus()。
答案 1 :(得分:0)
我只是花了一些时间来解决类似的问题,而我所得出的结论是,在子框架中运行的脚本不断将焦点转回到该框架。然后,当脚本终止时,子框架已被删除,因此浏览器不知道在哪里聚焦。
我如何解决这个问题是在父(或顶部)框架中创建一个函数,首先删除子框架,然后将焦点恢复到自身。现在,从子框架中,我只需调用父函数,即可修复它。
示例强>:
outer.html:
<!DOCTYPE html>
<html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" /></head><body>
Outer content - press [Enter] to load the iframe
<div id="iframeHolder"></div>
<script src="//ajax.googleapis.com/ajax/libs/prototype/1.7.2.0/prototype.js"></script>
<script>
// Create a function for the child frame to call
function regainFocus(){
$('iframeHolder').update('');
window.focus();
}
// When the outer document loads, start handling keystrokes
Event.observe(window, 'load', function(){ Event.observe(window, 'keyup', function(e){
// Catch only the Enter key
if((e.which||window.event.keyCode) != Event.KEY_RETURN) return;
// Construct the iframe, set its src, add it to holder, and focus on it
var frame = $(document.createElement('iframe'));
frame.setAttribute('src', 'inner.html');
frame.observe('load', function(){ this.contentWindow.focus(); });
$('iframeHolder').appendChild(frame);
});});
</script>
</body></html>
inner.html:
<!DOCTYPE html>
<html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" /></head><body>
Inner content - press [Esc] to close the iframe
<script src="//ajax.googleapis.com/ajax/libs/prototype/1.7.2.0/prototype.js"></script>
<script>
// When the inner document loads, start handling keystrokes
Event.observe(window, 'load', function(){ Event.observe(window, 'keyup', function(e){
// Catch only the Esc key
if((e.which||window.event.keyCode) != Event.KEY_ESC) return;
// Call the parent's function
parent.regainFocus();
});});
</script>
</body></html>