[英]jQuery: Detect when focus leaves an element's children, then give focus back to a triggering element
我有一個模態窗口腳本,我們正努力提高其可訪問性要求。 要求說,當您離開窗口跳格時,它應該關閉。 它還說,關閉窗口后,原始觸發元素必須重新獲得焦點。
經過一些挖掘后,我發現了這一點: jQuery找出父對象是否失去了“焦點” 。 似乎最簡單的判斷何時離開窗口的方法是跟蹤focusin事件,以及當焦點在不是打開模式的子元素的元素上觸發時,關閉窗口。 但是,如您所見,此方法是有問題的(更不用說對我而言太重了)。 這是處理此問題的代碼:
$('body').focusin(function(e) {
if (!$(e.target).parent().is('.current-window')) {
closeModal();
}
});
和關閉窗口的功能:
function closeModal() {
$('.modal-mask, .current-window').fadeOut('fast', function(){
$(this).removeClass('current-window');
$('.modal-mask').removeAttr('style');
$('.modal-trigger').focus();
});
}
現在很明顯,當我運行此代碼時,closeModal()在focusin事件直至最大調用堆棧之間來回觸發,因此在將焦點集中到觸發元素之前引發“超出最大調用堆棧”錯誤消息。
有關完整的代碼,請參考此提琴: http : //jsfiddle.net/pbredenberg/wxX4T/
我正在嘗試一種更好的方法來處理此要求,或者至少避免無限循環。 誰能指出我正確的方向?
我仍然不能只發表評論,所以我必須將其作為回答:為什么不跟蹤是否實際上是使用像window.closing這樣的布爾變量關閉窗口? 我更新了示例: http : //jsfiddle.net/kevkong/wxX4T/8/這是您要做什么?
每當您打開模態時,都應存儲對所單擊元素的引用。 然后,當模態關閉時,您可以檢索該模態並重新聚焦該元素。
工作演示: http : //jsfiddle.net/wxX4T/12/
function closeModal(e) {
if (e) e.preventDefault();
// Rather than using a .current-window class
// we can use the jQuery :visible pseudo-selector
var $window = $(".window:visible");
// Get our refernce to the focus target that was
// stored when the window was open.
var $trigger = $window.data("focusTarget");
// Close the window and mask
$('.modal-mask, .window').fadeOut('fast', function() {
// Focus on the original trigger
$trigger.focus();
});
}
$('.modal').click(function(e) {
e.preventDefault();
var $trigger = $(this);
var $modal = $($trigger.attr("href")).fadeIn(300)
$('.modal-mask').fadeIn(200);
// I have omitted all the code that positions
// the window (for the sake of clarity)
// Feel free to add it back.
// Store a reference to the trigger link in the modal's "data" hash
// so that when we close it later, we can retrieve the original
// trigger that opened the window.
$modal.data("focusTarget", $trigger);
});
// Trigger window close based on Tab key
$(document).on("keydown", function(e) {
// Only close modal if the tab key is pressed
// AND if there is a visible modal window.
if ((e.keyCode || e.which) === 9 && $(".window:visible").length > 0) {
e.preventDefault();
closeModal();
}
});
$(document).on("click", ".window .close", closeModal);
$(document).on("click", ".modal-mask", function() {
$(this).hide();
closeModal();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.