0

我在从 div 中分离 mouseout 事件时遇到问题。我从这个论坛(链接)中提取了该功能。其目的是防止事件冒泡。它就像一个魅力,但分离失败。每次我附加和分离时,Ik 都会不断增加事件处理程序。经过数小时的尝试......也许其他人有答案:-)

我的 HTML:

<div id="dd_301" onclick="dd_show(this,301)">
    <span id="sel_301">selected item</span>
    <div id="sel_A301" style="display:none">
        <div id="sel_B3010" onclick="dd_click(this,1)">option 1</div>
        <div id="sel_B3011" onclick="dd_click(this,2)">option 2</div>
    </div>
</div>

的JavaScript:

function dd_show(p, i) {
    getObj('sel_A' + i).style.display = 'block';
    addEvent(p, 'mouseout', makeMouseOutFn(p));
}

function dd_remove(o) {
    removeEvent(o,'mouseout',makeMouseOutFn);
    o.getElementsByTagName('div')[0].style.display = 'none';
}

function dd_click(o,i){
   var p=o.parentNode.parentNode;
   dd_remove(o);
   }

function addEvent(elem, ev, fn) {
    function listenHandler(e) {
        var ret = fn.apply(this, arguments);
        if (ret === false) {
            e.stopPropagation();
            e.preventDefault();
        }
        return (ret);
    }

    function attachHandler() {
        var ret = fn.call(elem, window.ev);
        if (ret === false) {
            window.ev.returnValue = false;
            window.ev.cancelBubble = true;
        }
        return (ret);
    }
    if (elem.addEventListener) {
        elem.addEventListener(ev, listenHandler, false);
    } else {
        elem.attachEvent("on" + ev, attachHandler);
    }
}

function removeEvent(o, ev, fn) {
    if (o.removeEventListener) {
        o.removeEventListener(ev, fn, false);
    } else {
        if (o.detachEvent) {
            o.detachEvent(ev, fn);
        }
    }
}

function makeMouseOutFn(elem) {
    var list = traverseChildren(elem);
    return function onMouseOut(event) {
        var e = event.toElement || event.relatedTarget;
        if ( !! ~list.indexOf(e)) {
            return;
        }
        alert('MouseOut');
    };
}

function traverseChildren(elem) {
    var children = [];
    var q = [];
    q.push(elem);
    while (q.length > 0) {
        var elem = q.pop();
        children.push(elem);
        pushAll(elem.children);
    }

    function pushAll(elemArray) {
        for (var i = 0; i < elemArray.length; i++) {
            q.push(elemArray[i]);
        }
    }
    return children;
}

[编辑]最后,冒泡以某种方式阻止了 onclick 的删除。添加

if('bubbles' in event){if(event.bubbles){event.stopPropagation();}}else{event.cancelBubble=true;}

成功了

4

0 回答 0