开发者

Issue with hover events 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 kind of behavior:

  1. Hover on a div. That particular div changes background color, and its children don't.
  2. Hover on that div's child. Again, it changes color while its children don't, AND(important) its parent reverts to its original color.
  3. Go back up to the parent div. Child reverts to original color, parent once again changes color.

The first two steps are easy:

$(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 hit a snag on that last step, because when I enter a child div the mouseenter event is still active on the parent; all I've done is make it look like it isn't. The only way to trigger the mouseleave on the parents is to exit the nested block entirely and enter again. Is there a way around this?


Add a mouseleave event to the parent and remove the parent's color on that.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜