创建的DIV内部的链接导致悬停时删除了DIV

Link inside created DIV cause the div removed on hover

本文关键字:DIV 删除 悬停 内部 链接 创建      更新时间:2023-09-26

这是我的代码:

var tagDes = document.createElement('DIV');
                    tagDes.className = 'tagDes';
                    tagDes.style.cssText = 'position:absolute;'+
                                    'background:#282828;'+
                                    'color:#fff;'+
                                    'padding:10px;'+
                                    'top:'+(posX+hei)+'px;'+
                                    'left:'+(posY+wid)+'px;'+
                                    'font-size:10pt;';
                    tagDes.onmouseout = function(){
                                        $(this).remove();
                                    };
                    $('#main-container').append(tagDes);
                    $('.tagDes').append(array[5]+'<a class="tagMenu">sdsdssds</a>');

posX,posY,hei,wid是指用于定位的元素。array[5]是一个字符串。我想将鼠标悬停在li上,然后创建包含链接(tagMenu类)的div(看起来像title属性)。但是,当我将链接悬停在该div内时,div将remove()。我要找的是,当我悬停在链接上时,div仍然可见,当我从中mouseout时,它将从页面中删除。有什么建议吗?请帮帮我。

试试这样的东西:

 tagDes.onmouseout = function(e){
 if (e.toElement.parentNode == this || e.toElement == this) {
       return;
     }
   $(this).remove();
   };

如果我理解正确,您希望将onmouseout事件绑定到内部链接元素。然后代码可以是这样的(我使用了更多的jQuery来简化它):

var $tagDes = $('<div class="tagDes"></div>').css({
    background: '#282828',
    color: '#fff',
    padding: '10px',
    top: (posX + hei) + 'px',
    left: (posY + wid) + 'px',
    fontSize: '10pt'
})
.append(array[5] + '<a class="tagMenu">sdsdssds</a>')
.appendTo('#main-container');
$tagDes.on('mouseleave', function() {
    $tagDes.remove();
});