我试图让图片库在单击链接时出现,并在单击浏览器窗口中的任何位置时消失。我可以更改与单击“galleryshow”元素关联的功能,这样,如果我单击它,则会显示图库,如果再次单击它,图库就会消失;但如果我尝试这样做,以便单击窗口(或文档)时图库将关闭,则不会发生任何情况。
这是我的代码:
function gallerymake() {
document.onclick = function () {gallerytake();};
// document.getElementById("hoverage").onclick = function() {gallerytake();};
document.getElementById("galleryhold").style.visibility="visible";
}
function gallerytake(){
document.getElementById("hoverage").onclick = function () {gallerymake();};
document.getElementById("galleryhold").style.visibility="hidden";
}
谢谢
最佳答案
freejosh 的答案有效。但是,如果有其他处理程序使用事件委托(delegate),则调用 e.stopPropagation()
可能会产生不良副作用,因为这些处理程序可能不会被调用。
事件处理的基础知识之一是它们不应该尽可能影响或依赖其他处理程序,例如,如果您有两个按钮需要显示两个不同的 div。通过调用e.stopPropagation()
,clicking on one of the popups would not hide the other popup 。请参阅document.click keep toggling the menu例如,它与灯箱事件处理程序发生冲突后无法正常工作。因此,不影响任何其他代码的解决方案是安装一个文档单击处理程序,该处理程序仅在单击不是来自按钮或弹出窗口内时才起作用。
HTML
Here is my web page <button id="show-btn"> show popup</button>
<div id="modal" > I will show over everything <a href="http://google.com" target="_blank">Google</a></div>
JS
var modal = document.getElementById('modal');
var btn = document.getElementById('show-btn');
btn.onclick = function() {
modal.style.display = "block";
};
document.onclick = function (e) {
e = e || window.event;
var target = e.target || e.srcElement;
if (target !== btn && (!target.contains(modal) || target !== modal)) {
modal.style.display = 'none';
}
}
您可以将此模式抽象为 function that creates the doc click handlers
/**
* Creates a handler that only gets called if the click is not within any
* of the given nodes
* @param {Function} handler The function to call (with the event object as
* as its parameter)
* @param {HTMLElement} exclude... If the click happens within any of these
* nodes, the handler won't be called
* @return {function} A function that is suitable to be
* bound to the document click handler
*/
function createDocClickHandler(handler /* [,exclude, exclude, ...] */) {
var outerArgs = arguments;
return function (e) {
e = e || window.event;
var target = e.target || e.srcElement;
// Only call the original handler if the click was outside all the excluded nodes
var isWithinExcluded = false;
for (var i=1; i < outerArgs.length; i++) {
var excluded = outerArgs[i];
if (target === excluded || excluded.contains(target)) {
isWithinExcluded = true;
break;
}
}
if (!isWithinExcluded) {
handler.call(this, e);
}
}
}
var modal = document.getElementById('modal');
var btn = document.getElementById('show-btn');
btn.onclick = function() {
modal.style.display = "block";
};
// Assign the handler that will hide the popup if the clicked
// happened outside of modal and btn
document.onclick = createDocClickHandler(function (e) {
modal.style.display = 'none';
}, modal, btn);
关于javascript - JS 菜鸟——为什么 document.onclick 无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13752689/