鼠标悬停不起作用

时间:2013-07-31 05:21:06

标签: javascript

我有一个等待移动事件的div。然后,它会为其提供一个包含信息的div。

我遇到的问题是正确删除事件监听器&还删除它创建的div ...由于某种原因,它无法找到我创建的子div。

所以这是我试过的剧本:

div.addEventListener('mouseover',bubble_info,false);


function bubble_info(e){
    var x = e.pageX + 50; //push it 50px to the right
    var div = document.createElement('div');
        div.style.position = 'absolute';
        div.style.top = e.pageY;
        div.style.left = x;
        div.className = 'bubble';
        div.innerHTML = 'Testing this div';     
        this.appendChild(div);

//stop firing if mouse moves around on the parent as it is still "over" the parent
    this.removeEventListener('mouseover',bubble_info,false); 

//when mouse out occurs the below should fire
    this.addEventListener('mouseout',function(){clear_hover.call(this,div);},false);
}


function clear_hover(child){
    //remove the bubble div we made
    child.parentNode.removeChild(child); 

    //remove the mouse out as we are now out
    this.removeEventListener('mouseout',function(){clear_hover.call(this,div);},false);

    //re-add the mouseover listener encase user hovers over it again
    this.addEventListener('mouseover',bubble_info,false);
}

任何人都可以看到我在这里犯的错误,只是无法解决为什么鼠标一切都出错了。

开发工具显示Cannot call method 'removeChild' of null

1 个答案:

答案 0 :(得分:1)

错误表明child.parentNode == null。因此,该元素没有parentNode从中删除。

if (child.parentNode)
    child.parentNode.removeChild(child);

但是,这只能解决症状。实际问题是没有删除事件处理程序,因此它会随后发生mouseout次运行。

虽然以下功能相似,但删除成功时需要相同。

this.addEventListener('mouseout',function(){clear_hover.call(this,div);},false);
this.removeEventListener('mouseout',function(){clear_hover.call(this,div);},false);

因此,您需要保存对function的引用以将其删除:

function bubble_info(e){
    var ...;

    function on_mouseout() {
        // pass a reference to the `function` itself
        clear_hover.call(this, div, on_mouseout);
    }

    // ...

    this.addEventListener('mouseout',on_mouseout,false);
}

function clear_hover(child, handler){
    //remove the bubble div we made
    child.parentNode.removeChild(child); 

    //remove the mouse out as we are now out
    this.removeEventListener('mouseout',handler,false);

    // ...
}