0

我有一个包含 Bootstrap 模式的主干视图。在那个观点上,我试图让 Esc 键关闭模式,但它是否有效,似乎取决于<div>'tabindex属性的存在:

var ModalView = Backbone.View.extend({
    el: '#modalOverlay', // is an existing container for modals

    events: {
        'keypress': function(event) { ... }
    },

    initialize: function(options) {
        // the view pattern
        this.compiledTemplate = Handlebars.compile(yesNoQuestionAlertTemplate);
        this.options = options;
        this.render(options);
    },
});

yesNoQuestionAlertTemplate包含属性,该tabindex属性定义了对转义键的正确处理。当我删除属性时,转义不起作用,当我把它放回去时,处理程序被正确触发。

<div id="yesNoQuestion" class="modal large" tabindex="-1" aria-hidden="true">
     <!-- modal definition -->
</div>

为什么会存在这种奇怪的依赖关系?

4

1 回答 1

3

事件的目标keypress只能是可以有焦点的元素。默认情况下,输入元素可以具有焦点。要使任何其他 HTML 元素具有焦点,您需要为其分配一个tabindex属性。

当一个元素获得焦点时,事件会在 DOM 中冒泡并在所有父元素上触发。所以你必须选择:

  • 您应该为元素分配tabindex属性。
  • 赶上事件bodywindow因为他们是所有元素的父母。
于 2013-06-10T13:03:46.267 回答