javascript 元素 body.onclick 附加事件 setTimeout

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4267389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:49:57  来源:igfitidea点击:

javascript element body.onclick attatch event setTimeout

javascripteventsonclicksettimeout

提问by llamerr

I want to make popup div that disappears when i click outside of it. I need pure js, not a jQuery or something. So i do the following...

我想让弹出 div 在我点击它外面时消失。我需要纯 js,而不是 jQuery 或其他东西。所以我做了以下...

function that make div to dissapear:

使 div 消失的函数:

function closePopUps(){
    if(document.getElementById('contact-details-div'))
        document.getElementById('contact-details-div').style.display = 'none';
    //...same code further...
} 
function closePopUpsBody(e){
    //finding current target - http://www.quirksmode.org/js/events_properties.html#target
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;

    //is we inside div?    
    while (targ.parentNode) {
        //filtering "Close" button inside div
        if (targ.className && targ.className == 'closebtn')
            break;
        if (targ.className && targ.className == 'contact-profile-popup')
            break;
        targ = targ.parentNode;
    }
    //if it not a div, or close button, hide all divs and remove event handler
    if ((targ.className && targ.className == 'closebtn')
        || !(targ.className && targ.className == 'contact-profile-popup')) {
        if(document.getElementById('contact-details-div'))
            document.getElementById('contact-details-div').style.display = 'none';
        //...some more code here...

        document.body.onclick = null;
    }
}

maybe this code is ugly, but this not a main problem...

也许这段代码很难看,但这不是主要问题......

main problem is when i attach an event to body, it executes immediately! and div dissapears immediately, i even don't see it.

主要问题是当我将事件附加到正文时,它会立即执行!和 div 立即消失,我什至没有看到它。

<tr onclick="
closePopUps();
document.getElementById('contact-details-div').style.display='block';
document.body.onclick = closePopUpsBody;
return false;">

i though if i don't use parentheses, it will not executes?

我虽然如果我不使用括号,它不会执行?

document.body.onclick = closePopUpsBody(); //this executes
document.body.onclick = function(){closePopUpsBody()}; //this is not
document.body.onclick = closePopUpsBody; //this is not

finally i finished with this decision

最后我完成了这个决定

<tr onclick="
closePopUps();
document.getElementById('contact-details-div').style.display='block';
setTimeout('document.body.onclick = closePopUpsBody;', 500);
return false;">

but i think this is madness. so, what i am doing wrong?

但我认为这太疯狂了。那么,我做错了什么?

采纳答案by gblazex

You should stop event bubbling. Simple [demo]

你应该停止事件冒泡。简单 [演示]

var box = document.getElementById('box');
var close = document.getElementById('close');

// click on a box does nothing
box.onclick = function (e) {
  e = e || window.event;
  e.cancelBubble = true;
  if (e.stopPropagation)
    e.stopPropagation();
}

// click everywhere else closes the box
function close_box() {
  if (box) box.style.display = "none";
}

close.onclick = document.onclick = close_box;

回答by Arsen7

Usually events are propagated to the parents. If you click on a <div>, then <body>also will have its onClick called.

通常事件被传播给父母。如果你点击 a <div>,那么<body>它的 onClick 也会被调用。

The first thing is: debug the order of called functions: place window.dump("I am called!")kind of things in your handlers.

第一件事是:调试被调用函数的顺序:window.dump("I am called!")在处理程序中放置一些东西。

I suppose you need to call event.stopPropagation()somewhere in your code. (See https://developer.mozilla.org/en/DOM/event)

我想您需要event.stopPropagation()在代码中的某个地方调用。(见https://developer.mozilla.org/en/DOM/event

About the parentheses question:

关于括号问题:

document.body.onclick = closePopUpsBody;//this is not
document.body.onclick = closePopUpsBody();//this executes

This executes, because you are calling a function closePopUpsBody() to return a value which will be assigned to the onclick property. In JavaScript the function name represents the function object (as any other variable). If you place parentheses after a variable name, then you say: 'execute it for me, as a function`.

这会执行,因为您正在调用函数 closePopUpsBody() 以返回一个将分配给 onclick 属性的值。在 JavaScript 中,函数名代表函数对象(与任何其他变量一样)。如果您在变量名后放置括号,那么您会说:“为我执行它,作为一个函数”。

回答by Ioannis Karadimas

Here 's a full example of how you could accomplish that.

这是一个完整的示例,说明如何实现这一目标。

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title></title>
    <style>
        body { font-family: Tahoma; font-size: 1.1em; background: #666666; color: White; }
        #layer01 { border: 1px solid black; width: 200px; height: 100px; position: absolute; 
                   top: 100px; left: 100px; background: white; padding: 10px; color: Black;
                   display: block; }
    </style>
</head>
<body>
    Click anywhere outside the layer to hide it.

    <div id="layer01"> Test Layer </div>

    <script type="text/javascript">
        isIE = (window.ActiveXObject) ? true : false;

        document.onclick = function (e) {
            var l = document.getElementById("layer01");

            if (!isIE && e.originalTarget == l)
                e.stopPropagation();
            else if (isIE && event.srcElement == l)
                event.cancelBubble = true;
            else 
                l.style.display = "none";
        }

    </script>
</body>
</html>