[英]JS function when clicking parent element but return false when clicking child element
我的網站上有一個圖片庫,當您單擊它時,它就會變成燈箱效果。
我希望他們能夠單擊燈箱背景上的預覽圖像並關閉預覽,但如果他們單擊實際的預覽圖像本身,則不能。
function get_image_preview(){
var lightbox = document.getElementById("lightbox");
var image_src = document.getElementById("gallery_image").src;
lightbox.style.display = "block";
lightbox.setAttribute("onclick", "end_image_preview()");
var new_image = document.createElement("img");
new_image.setAttribute("id", "preview_image");
new_image.setAttribute("src", image_src);
new_image.setAttribute("onclick", "return false");
lightbox.appendChild(new_image);
}
function end_image_preview(){
var lightbox = document.getElementById("lightbox");
lightbox.style.display = "none";
lightbox.innerHTML = "";
}
所以基本上這行:
lightbox.setAttribute("onclick", "end_image_preview()");
執行應做的操作並關閉預覽。
但是,預覽是此的子級,我希望他們能夠在不結束預覽的情況下單擊圖像,因此我嘗試了以下操作:
new_image.setAttribute("onclick", "return false");
我認為您想使用event.stopPropagation() :
function new_image_click(e) {
e.stopPropagation();
}
new_image.setAttribute("onclick", "new_image_click(event)");
在最終圖像預覽中,單擊偵聽器確保該元素在其祖先中沒有自身的預覽元素,可以說您給預覽元素指定了ID“ preview”
在end_image_preview中
function end_image_preview(e) {
if (e.closest('#preview')) {
return
}
// here do what you already doing
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.