当用户使用JavaScript在某些div中单击时,如何停止事件

时间:2012-01-13 17:58:59

标签: javascript events

我希望此代码检查用户是否已在打开的框内单击,如果是,则会保持打开状态,如果用户在框外单击它将关闭。

http://jsfiddle.net/MTJa5/26/

var boxes = function(){
    var divClicks = document.getElementsByClassName("clickToShow");
    for(i=0; i < divClicks.length; i++){
        var click = divClicks[i];

        var clickEvent = function(){
            click.addEventListener("click", function(e){
                var currentClass= this.getElementsByTagName('div')[0].className;
                var divs = document.getElementsByClassName('openedBox');
                for(var i = 0; i < divs.length; i++){
                    divs[i].setAttribute("class", "closedBox");

                }

                if(currentClass === "openedBox"){
                    this.childNodes[3].setAttribute("class", "closedBox");
                } else {
                    this.childNodes[3].setAttribute("class", "openedBox");

                }
            },false);
        }();
    }
}();

1 个答案:

答案 0 :(得分:1)

您也可以只绑定一个click事件,而不是绑定多个事件侦听器,并使用event.target属性来检查您点击的位置。

更新的代码不那么复杂,也更容易维护。

演示:http://jsfiddle.net/MTJa5/28/

 var hellos = function() {
     function closeAllButThisBox(targ) {
         var allBoxes = document.getElementsByClassName('openedBox');
         for (var i=allBoxes.length-1; i>=0; i--) {
             if (allBoxes[i] !== targ) {
                 allBoxes[i].className = 'closedBox';
             }
         }
     }
     window.addEventListener('click', function(ev) {
         var targ = ev.target;
         // Traverse the tree, until you hit the desired / root element
         while (targ && targ !== document.documentElement) {
             if (targ.className.indexOf('openedBox') !== -1) {
                 closeAllButThisBox(targ);
                 // Do nothing when clicking inside an opened box
                 return;
             }
             // This will open boxes, if closed, when clicking at the <p>
             if (targ.tagName.toLowerCase() === 'p' && targ.parentNode.className.indexOf('clickToShow') !== -1) {
                 closeAllButThisBox(targ.parentNode);
                 targ.parentNode.getElementsByTagName('div')[0].className = 'openedBox';
                 return;
             }
             targ = targ.parentNode;
         }

         // At this point, the click is not at the right place.
         // Close all boxes by removing the closedBox class names
         var boxes = document.getElementsByClassName('openedBox');
         for (var i=boxes.length-1; i>=0; i--) {
             boxes[i].className = 'closedBox';
         }
     }, false);
 }();