我有一个可以有 n 个嵌套 div 标签的环境。我必须只在子 div 中跟踪鼠标的鼠标移动时刻。
我有以下代码。结果显示在列表中。
问题:如果我追加更多子“div”,鼠标移动也会跟踪所有父 div。
我想要的:仅获取鼠标悬停区域的鼠标轨迹。
我还尝试使用 is:hover 进行过滤,但所有元素都悬停了。 JSFIddle
var count = 0;
$('div').on({
mousemove: function(event) {
$('.mousemovement').append('<li>MouseMove' + $(this).attr('class') + '</li>');
if (count > 10) {
$('.mousemovement').html('');
count = 0;
}
count++;
}
});
.outer {
background-color: #aeaeae;
height: 200px;
width: 200px;
float: left;
}
.inner {
margin: 5px 0px;
background-color: #ccc;
height: 100px;
width: 100px;
float: left;
}
.inner2 {
margin: 5px 0px;
background-color: green;
height: 60px;
width: 60px;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="outer">
<div class="inner">
<div class="inner2">
</div>
</div>
</div>
<ul class="mousemovement">
</ul>
最佳答案
你应该使用 event.stopPropagation() ,检查下面的片段。
Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
希望这对您有所帮助。
var count = 0;
$('div').on({
mousemove: function(event) {
event.stopPropagation();
$('.mousemovement').append('<li>MouseMove' + $(this).attr('class') + '</li>');
if (count > 10) {
$('.mousemovement').html('');
count = 0;
}
count++;
}
});
.outer {
background-color: #aeaeae;
height: 200px;
width: 200px;
float: left;
}
.inner {
margin: 5px 0px;
background-color: #ccc;
height: 100px;
width: 100px;
float: left;
}
.inner2 {
margin: 5px 0px;
background-color: green;
height: 60px;
width: 60px;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer">
<div class="inner">
<div class="inner2">
</div>
</div>
</div>
<ul class="mousemovement">
</ul>
关于javascript - 仅跟踪嵌套 div 标记中悬停子元素的鼠标移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35551847/