当鼠标悬停在其子元素上时,如何防止父元素的 mouseout 触发?
假设我有一个红色正方形图像,当鼠标经过它时,它会变成绿色,当鼠标离开正方形时,它会变回红色。然后我用它做了一个菜单之类的东西,这样当我将鼠标悬停在广场上时,它会变成绿色,并且在其下方出现一个矩形。
我想要发生的是:矩形出现后,我将鼠标移出正方形并移到矩形上方,我希望正方形保持绿色,直到我将鼠标移出矩形。
我如何用 jquery 做到这一点?我使用的代码是这样的:
$('.square').hover(function() {
$(this).addClass('.green');
}, function() {
$(this).addClass('.red');
});
$('.square').hover(function() {
$(this).children('.rectangle').show();
}, function() {
$(this).children('.rectangle').hide();
});
So let's say I have a red square image that turns green when the mouse goes over it, and it turns back to red when the mouse leaves the square. I then made a menu sort of thing with it so that when I hover on the square, it turns green and a rectangle appears below it.
What I want to happen is this: After the rectangle appears and I move the mouse out of the square and over the rectangle, I want the square to remain green until I move the mouse out of the rectangle.
How do I do this with jquery? The code i use is something like this:
$('.square').hover(function() {
$(this).addClass('.green');
}, function() {
$(this).addClass('.red');
});
$('.square').hover(function() {
$(this).children('.rectangle').show();
}, function() {
$(this).children('.rectangle').hide();
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的代码中只有一些错误。
jQuery:
CSS:
You have just a few errors in your code.
jQuery:
CSS:
我最近也遇到了同样的问题。我所做的就是向“子”元素添加一个
mouseenter
事件,这样在从父元素传递到子元素时它就不会被关闭。基本上,我在两个元素上都有mouseenter
和mouseleave
(当然,这两个元素稍微重叠)。I have recently had the same problem. What I did was adding an
mouseenter
event to the "child" element too so while passing from parent to child it's not turned off. Basically I havemouseenter
andmouseleave
on both elements (which of course are slightly overlapping for this to work).如果菜单位于方块内,您可以尝试如下操作:
If the menu is inside the square you can try something like this: