How to disable parent hover, when hovering over ch

2019-06-22 09:42发布

问题:

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

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.

What's the problem?
The problem is, when I hover over yellow part, i want to change background of yellow element, but i don't want to parent :hover to work.

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

Those are only css rules about hovering so far

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

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?

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
    }
});

回答1:

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');
});

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.

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



回答2:

You might want to see this question, which talks about nesting CSS classes. This might allow you to set .przycisk's color to it's default when .skrot is being hovered over.