悬停在孩子上时如何禁用父悬停

2022-01-22 00:00:00 hover jquery html css

我会尝试用一些简单的例子来说明我的问题.

I will try to show my problem on some simple example.

我有什么?
http://jsfiddle.net/JGzSh/3/
这是一些简单的按钮,稍后会有 onlick 事件.当我将鼠标悬停在绿色 div(父级)上时,:hover 会稍微改变它的颜色.

What I have?
http://jsfiddle.net/JGzSh/3/
Here is some simple button, which will have onlick events later. When i hover over green div (parent), :hover works changing its color a bit.

有什么问题?
问题是,当我将鼠标悬停在黄色部分上时,我想更改黄色元素的背景,但我不想让 :hover 工作.

问题
那么如何在鼠标悬停在孩子上时禁用父 :hover ?(所以父母的背景会回到起始颜色?)

Question
So how can i disable parent :hover when hovering over child? (so parent's background will go back to starting color?)

到目前为止,这些只是关于悬停的 CSS 规则

Those are only css rules about hovering so far

.przycisk:hover{
    background-color: #383;
}
.skrot:hover{
    background-color: red;
}

到目前为止我尝试了什么?
这是最重要的问题,我知道.我做了一些研究,到目前为止,我找到了一些可以帮助我的解决方案,但它们都使用 jQuery,我的问题是,是否可以仅在 CSS 中完成,以使其保持简单尽可能?

What have I tried so far?
Thats most important question, I know. I did some research, and so far i found some solutions which could help me, but they all use jQuery, and my question is, if its possible to do it in CSS only, to keep it as simple as possible?

在 google 中找到的 jQuery 解决方案示例:

Example of solution in jQuery found in google:

$('.przycisk').hover(function(e){
    if($(e.target).is('.skrot')){
        // your child span is being hovered over
        e.stopPropagation();
    }else if($(e.target).is('.przycisk')){
        // your parent element is being hovered over
    }
});

推荐答案

我想我找到了一些非常快速的解决方案.

I think i found some pretty quick solution for that.

$('.deHover').hover(function(){
    $(this).parent().css('background-color', '#008000');
}, function(){
    $(this).parent().css('background-color', '#383');
});

$('.przycisk').hover(function(){
    $(this).css('background-color', '#383');
}, function(){
    $(this).css('background-color', '#008000');
});

对于我想要禁用父悬停的所有内容,我添加了 deHover 类,它只是在 mousein/mouseout 上更改父背景颜色.但我还需要记住让 Parent 悬停(进出)工作,所以我也为它添加了一个 jQuery.

To everything what I want to be disabling parent hover, I add deHover class, and it just changes parent background color on mousein/mouseout. But i also need to remember to make Parent hover (in and out) work, so i added an jQuery for it also.

这里是 jsfiddle 检查它是否有效.没有发现任何可抱怨的地方.

Here is jsfiddle to check if it works. Didn't find anything to complain about.

相关文章