[英]Backbone: 'keypress' event handler depends on div's tabindex?
我有一個包含Bootstrap模態的Backbone視圖。 在這種情況下,我試圖使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>
為什么存在這種奇怪的依賴關系?
keypress
事件的目標只能是可以具有焦點的元素。 輸入元素默認可以具有焦點。 為了使其他任何HTML元素都具有焦點,您需要為其分配一個tabindex
屬性。
當一個元素成為焦點時,事件就會在DOM上冒出,並在所有父元素上觸發。 因此,您必須選擇:
tabindex
屬性。 body
或window
上捕獲事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.