onmouseover在内部元素上执行

onmouseover executes on inner elements

本文关键字:执行 元素 在内部 onmouseover      更新时间:2023-09-26

我有一个div,它是一些文本的包装器:

<div class="timeSpanWrapper" data-occupied="false">
    <span>@day.ToString("HH:mm", new System.Globalization.CultureInfo("da-DK"))</span>
</div>

当我把鼠标放在包装上时,我想执行一个函数:

$(".timeSpanWrapper").on("mouseover", function (evt) {
    if (evt.ctrlKey) {
        setTimeSlot($(this));
    }
});

该函数会被执行,但如果我将<span>悬停在timeSpanWrapperdiv中,它也会被执行——这不是我想要的,因为该方法将被激发两次。

对此有什么解决方法?

注意:

我尝试了一下建议的答案。当我将鼠标悬停在span上时,该方法不会被执行,但当我再次将span留给父div时,它会被执行,这是一个问题,因为父div是一个中心有一些文本的框。

您可以通过确保目标是绑定元素来确保它不会在子元素上执行

$(".timeSpanWrapper").on("mouseover", function (evt) {
    if (evt.ctrlKey && this === evt.target) {
        setTimeSlot($(this));
    }
});

或者只使用mouseenter事件,在这里似乎更合适

$(".timeSpanWrapper").on("mouseenter", function (evt) {
    if (evt.ctrlKey) {
        setTimeSlot($(this));
    }
});

您可以使用.not()函数来避免中的跨度

$(".timeSpanWrapper").not(".timeSpanWrapper span").on("mouseover", function (evt) {
    if (evt.ctrlKey) {
        setTimeSlot($(this));
    }
});

之所以会发生这种情况,是因为mouseover事件在其子元素中冒泡。您需要使用mouseenter来避免这种情况。

尝试在jsfiddle演示中用mouseover更改mouseenter

$(".timeSpanWrapper").on("mouseenter", function (evt) {
     $('body').append('<span>entered</span>');
});