javascript 元素 body.onclick 附加事件 setTimeout

发布于 2024-10-04 04:04:58 字数 2179 浏览 2 评论 0原文

我想制作一个弹出 div,当我点击它外部时它就会消失。我需要纯js,而不是jQuery 之类的。 所以我做了以下...

使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;
    }
}

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

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

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

我想如果我不使用括号,它就不会执行?

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

最后我完成了这个决定

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

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

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...

function that make div to dissapear:

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.

<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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浮生未歇 2024-10-11 04:04:58

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

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;

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;
黯然#的苍凉 2024-10-11 04:04:58

通常事件会传播给父母。如果您单击

,则 也会调用其 onClick。

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

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

(请参阅 括号问题:

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

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

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

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

I suppose you need to call event.stopPropagation() somewhere in your code. (See 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`.

琴流音 2024-10-11 04:04:58

这是如何实现这一目标的完整示例。

<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>

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文