Javascript 在孩子身上触发鼠标
我被困在一件很容易解决的事情上,但我无法做到。我希望在悬停父对象时更改其样式,但在悬停父对象的子对象时恢复正常 html:Javascript 在孩子身上触发鼠标,javascript,jquery,html,hover,Javascript,Jquery,Html,Hover,我被困在一件很容易解决的事情上,但我无法做到。我希望在悬停父对象时更改其样式,但在悬停父对象的子对象时恢复正常 html: <div id="parent"> <div id="child"></div> </div> $('#parent').on({ mouseenter: function (event) { event.stopPropagation(); event.stopImmediat
<div id="parent">
<div id="child"></div>
</div>
$('#parent').on({
mouseenter: function (event) {
event.stopPropagation();
event.stopImmediatePropagation();
$(this).css("box-shadow", "inset 0 0 0 1000px green");
},
mouseleave: function (event) {
event.stopPropagation();
event.stopImmediatePropagation();
$(this).css("box-shadow", "inset 0 0 0 0px pink");
}
});
小提琴:
<div id="parent">
<div id="child"></div>
</div>
$('#parent').on({
mouseenter: function (event) {
event.stopPropagation();
event.stopImmediatePropagation();
$(this).css("box-shadow", "inset 0 0 0 1000px green");
},
mouseleave: function (event) {
event.stopPropagation();
event.stopImmediatePropagation();
$(this).css("box-shadow", "inset 0 0 0 0px pink");
}
});
RiggsFolly评论将JS更改为:
$('#parent').on({
mouseenter: function (event) {
event.stopPropagation();
event.stopImmediatePropagation();
$(this).css("box-shadow", "inset 0 0 0 1000px green");
},
mouseout: function (event) {
event.stopPropagation();
event.stopImmediatePropagation();
$(this).css("box-shadow", "inset 0 0 0 0px pink");
}
});
$('#child').on({
mouseenter: function (event) {
event.stopPropagation();
event.stopImmediatePropagation();
$("#parent").css("box-shadow", "inset 0 0 0 0px green");
},
mouseleave: function (event) {
event.stopPropagation();
event.stopImmediatePropagation();
$("#parent").css("box-shadow", "inset 0 0 0 1000px green");
}
});
现在可以用了,谢谢里格斯 使用mouseover和mouseout并检测mouseover上触发的元素
$(“#父项”)。在({
鼠标悬停:函数(事件){
如果(!$(this).is(event.target))返回;
event.stopPropagation();
事件。stopImmediatePropagation();
$(this.css(“框阴影”,“插入0 1000px绿色”);
},
mouseout:函数(事件){
event.stopPropagation();
事件。stopImmediatePropagation();
$(this.css(“框阴影”,“插入0像素粉色”);
}
});代码>
#父级{
背景颜色:粉红色;
宽度:200px;
高度:200px;
}
#孩子{
位置:相对位置;
左:75px;
顶部:75px;
背景颜色:蓝色;
宽度:50px;
高度:50px;
}
如果您将鼠标悬停在父对象之后的子对象上,我猜您实际上并没有离开父对象。您可能需要在child.mouseenter事件和parent.mouseleaveemouse out事件中编写mouseleave
代码。mouseleaveemouse out会让您返回,但当再次离开孩子时,它不会触发鼠标进入。您是对的,这看起来更干净。如果可以,我会接受它!谢谢