悬停事件在第一次调用鼠标时停止鼠标输入事件

Hover event stopping a mouse enter event the first time its called.

本文关键字:鼠标 输入 入事件 悬停 第一次 调用 事件      更新时间:2023-09-26

我有一个项目列表,用户可以通过javascript添加到其中。我想要的是当用户将鼠标悬停在列表项上时,使字形图标可见。现在它可以工作,但只有在用户将鼠标移入然后将鼠标移出列表项之后。在他们这样做之后,一旦他们将鼠标移回列表项,它就会开始工作。

Jquery:

//When the user hovers over a list item give them the option to delete it
$('.list-item-container').hover(function(){
    $('.list-item').on({
        mouseover: function(){
            $('.glyphicon-remove', this).css('visibility', 'visible');
            //When the user click to remove the list item remove it from the list
            $('.glyphicon-remove').on('click', function(){
                //TODO: Popup modal for delete confirmation
                $(this).parent().remove();
            });
        },
        mouseout: function(){
            $('.glyphicon-remove', this).css('visibility', 'hidden');
        }
    });
});

Html:

<div class="list-item-wrapper">
    <ul class="list-item-container">
        <li class="row list-item">
            <input type="checkbox" class="item-done">
            <label for="list-done">My to-do-list</label>
            <span class="glyphicon glyphicon-remove pull-right"></span>
        </li>
    </ul>
</div>

您的jQuery代码将事件附加到mouseover上(每次都是这样-不太好)-所以您的代码没有按照您的意愿执行。

使用CSS,这要容易得多。

.glyphicon-remove {
    visibility: hidden;
}

.list-item-container:hover .glyphicon-remove {
    visibility: visible;
}

然后,唯一需要的JavaScript就是删除元素。

$('.list-item-container').on('click', '.glyphicon-remove', function() {
    $(this).parent().remove();
});