The problem with freezes and parents

So, let's say I have a block of nested divs:

<div class='nested'> <div class='nested'> <div class='nested'></div> </div> </div> 

I want this behavior:

  • Hover over the div. This particular div changes the background color, and its children do not.
  • Hover over this child. Again, he changes color until his children do it, AND (importantly) his parent returns to his original color.
  • Return to the parent div. The child returns to the original color, the parent changes color again.

The first two steps are simple:

 $(function() { $('.nested').bind('mouseenter',function() { $(this).css('background-color','#EEE'); $(this).parent().css('background-color','white'); }).bind('mouseleave',function() { $(this).css('background-color','white'); }); }); 

But I came across this last step, because when I introduce a child div, the mouseenter event is still active in the parent; all i did was make it look as if it weren’t. The only way to cause mouse movement on the parents is to completely close the nested block and re-enter it. Is there any way around this?

+4
source share
1 answer

Add the mouseleave event to the parent and remove the parent color.

 $(function() { $('.nested').bind('mouseenter',function() { $(this).css('background-color','#EEE'); $(this).parent().css('background-color','white'); }).bind('mouseleave',function() { $(this).css('background-color','white'); // put the color back on the parent $(this).parent().css('background-color', '#EEE'); }); // remove the color from the parent $(".parent").bind("mouseleave", function() { $(this).css('background-color','white'); }); }); 
+4
source

Source: https://habr.com/ru/post/1301622/


All Articles