鼠标悬停不起作用

Mouse over not working

本文关键字:不起作用 悬停 鼠标      更新时间:2023-09-26

我有一个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

错误表明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);
    // ...
}