[英]jQuery check if object element is inside another
我正在嘗試創建一個簡單的jQuery彈出菜單,但似乎無法找出腳本來檢查元素是否在預定義元素中。
單擊彈出窗口觸發器啟動jQuery函數。 該函數保存以下變量:單擊的元素(js_popup-trigger),其主要父級(js_popup-container)和帶有菜單項的實際菜單(js_popup-menu)。
單擊觸發器后,菜單會淡入/淡出,並且會在文檔中添加一個事件偵聽器以檢查用戶是否在菜單外單擊,在這種情況下它應該關閉,如果用戶單擊,菜單就不會發生任何事情在里面。
這是我無法弄清楚的部分 - 我如何檢測用戶是否已點擊彈出元素內部或外部?
我試過這個: if(!$(e.target).parent('.js_popup-container').length){
但是當你在頁面上有多個彈出窗口時,這不能很好地工作,因為如果你點擊其他任何地方,包括另一個彈出窗口,當前的一個應該關閉,但是如果你點擊另一個彈出窗口具有相同類的js_popup-container,那么它將保持打開狀態,因為它在技術上屬於該類的元素。
/* Popup menu toggle
===========================================*/
$(document).on("click",".js_popup-trigger", function(e){
e.preventDefault();
//Set variables
var element = $(e.currentTarget),
container = element.parent('.js_popup-container'),
menu = element.next('.js_popup-menu');
//Toggle the menu
menu.fadeToggle(200);
/* Create a click listener for the document
* This is to close the menu if clicked outside of it */
$(document).click(function closePopup(e){
//If the clicked item is not in the popup, close it
if(!$(e.target).parent(container).length){
menu.fadeToggle(200);
$(document).unbind('click',closePopup);
}
});
});
最后,我想要實現的是一個函數,只需添加3個類就可以應用於任何彈出菜單。 應該可以選擇在同一頁面上有多個彈出菜單,當單擊菜單外的任何位置時,它應該關閉。
當然我對改進代碼的建議持開放態度,但我現在不想使用預先存在的插件。
編輯:我知道已經有其他問題和解決方案與此非常相似,但區別在於其他問題中給出的解決方案是檢查被點擊的目標是否在具有特定類名/ id的另一個元素內/選擇器。
我需要一些不同的東西,我已經將父元素(彈出容器)保存在變量中。 我需要知道被點擊的元素是否在該已保存元素內。
使用已經找到的解決方案,我遇到了一個問題,因為我將在頁面上有多個彈出窗口,所以如果我打開一個彈出窗口,然后我點擊另一個彈出窗口,第一個彈出窗口將保持打開而不是關閉,這是因為使用其他解決方案,我正在檢查彈出容器類的元素,他們都有,這意味着第一個彈出窗口不會關閉。
這取決於你想要你的方法的性能,但這里有一個簡潔的選擇,假設元素和容器都是jQuery對象。
if(element.parents().find(container).length == 1){
// do work
}
我想出了一個適用於我當前應用程序的解決方案。
$(document).on("click",".js_popup-trigger", function(e){
e.preventDefault();
//Set variables
var element = $(e.currentTarget).closest('.js_popup-trigger'),
container = element.parent('.js_popup-container'),
menu = element.next('.js_popup-menu');
//Toggle the menu
menu.fadeToggle(200);
//Add the open classes to the container and trigger
container.toggleClass('js_popup-container--open');
element.toggleClass('js_popup-trigger--open');
/* Create a click listener for the document
* This is to close the menu if clicked outside of it */
$(document).click(function closePopup(e){
//If the clicked item is not in the popup, close it
if(!$(e.target).closest(container[0]).length && element.is(":visible")){
//Close the popup
menu.fadeOut(200);
//Remove the added classes
container.removeClass('js_popup-container--open');
element.removeClass('js_popup-trigger--open');
//Unbind the closePopup function from the document
$(document).unbind('click',closePopup);
}
});
});
這使得你可以在同一頁面上添加任意數量的彈出窗口,並且它們將獨立於其他人工作 - 我發現的所有其他解決方案都使用通用類來檢查彈出窗口是否打開而不是實際元素/對象,這意味着如果你有另一個彈出窗口打開同一個類,那么單擊一個新的彈出窗口將不會關閉第一個彈出窗口。 這種方法解決了這個問題。
希望這對其他人有幫助,如果有人有更好的想法,那么我很樂意聽到他們!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.