我只想通过使用下图中的 .hover()
函数将 border
仅放在蓝点下的“div”。但正如您所见,许多 div
元素周围都有红色边框。
我的代码是:
$(function(){
$("div").hover(function(e){
$(e.currentTarget).css({"border": "solid red 2px"})
}, function(e){
$(e.currentTarget).css({"border": "none"})
})
})
但是结果出乎意料,如上所述。 如何只突出显示光标下的 div?
谢谢 kdbanman - 答案在下面
我编辑这个问题是因为 kdbanman 的答案解决了我的问题,但应该添加更多的代码。这是完整的代码。
$(function(){
$("div").mouseover(function(e) {
e.stopPropagation();
if (e.redBorderDrawn) return;
$(this).css({"border": "solid red 2px"});
e.redBorderDrawn = true;
}).mouseout(function(e) {
$(this).css({"border": "none"})
});
});
最佳答案
问题是你的悬停事件是bubbling up your entire tree of div
elements ,所以使用 stopPropagation()
来防止事件在树上冒泡。
$(function(){
$("div").hover(function(e){
$(e.currentTarget).css({"border": "solid red 2px"})
e.stopPropagation();
}, function(e){
$(e.currentTarget).css({"border": "none"})
})
})
但是,对所有 div
元素在 hover
和 mouseout
上使用 .stopPropagation()
可能为他们杀死其他鼠标悬停行为/效果。上面的代码只是为了演示事件冒泡问题。在事件上设置自定义标志并允许它传播会更安全:
$(function(){
$("div").hover(function(e){
if (e.redBorderDrawn) return;
$(e.currentTarget).css({"border": "solid red 2px"});
e.redBorderDrawn = true;
}, function(e){
$(e.currentTarget).css({"border": "none"})
})
});
此外,当输入子元素时,不会调用 hover
的第二个回调(mouseleave
回调)。将相同的边框移除回调添加到 mouseout
事件以处理这种情况:
$(function(){
$("div").mouseout(function(e){
$(e.currentTarget).css({"border": "none"})
})
})
现在悬停行为如下所示:
关于javascript - 在 jquery 中,如何使用悬停功能仅突出显示光标下的 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32850677/