当子iframe获得焦点时,防止文档丢失键绑定

时间:2013-08-02 15:02:04

标签: javascript jquery html5 iframe

基本上我的目标是尝试为我的整个Web项目创建一个键盘控制器,我希望能够保留我在父文档上创建的键绑定,并让它们由子iframe继承。这可能吗?

以下是我现在所拥有的示例设置:http://jsfiddle.net/sahil_signal/d39Nn/9/

<div id="tabcontainer">
    <button id="tab1button" type="button">Tab1</button>
    <button id="tab2button" type="button">Tab2</button>
</div>
<iframe id="iframe1container"></iframe>
<iframe id="iframe2container"></iframe>

$(document).on('keydown', function (e) {
    var keycode = e.keyCode || e.which;

    if (keycode == 9) {
        e.preventDefault();
        console.log("Tab");
    }
});

我希望能够让tab键仍然绑定,即使iframe占据焦点,我也意识到我可以将tab键重新绑定到iframe文档,但有没有办法避免这种情况?

1 个答案:

答案 0 :(得分:2)

在你的iframe中,你可以添加一个触发top事件的事件处理程序...... 将这部分代码放在iframe文档中:

$(document).on('keydown', function (e) {
    $(top.document).trigger('keydown',e);
});

这应该只是将事件“转发”到顶层文档。请参阅jQuery API中的http://api.jquery.com/category/events/event-object/http://api.jquery.com/trigger/,以便能够稍微播放一下。

相关问题