jQuery:在parents()和children()上设置hover样式

3
我想知道当元素的父元素被悬停时,是否可能改变子元素的样式,同时也要更改其css。为了使我的问题更清楚,我在下面写了一个基本的代码:
   //styling child while mouse is inside child element
$('child').on('hover', function(e){
   if (e.type == 'mouseenter'){
      $(this).css('background','yellow');
   }
})

   // styling child while mouse is inside parent
$('child').parents().on('hover', function (e){
   if (e.type == 'mouseenter'){
      $(this).css('background', 'blue');
   }
})

基本上,一旦用户进入父级空间使子元素的背景变成蓝色,一旦进入子级空间将背景从蓝色更改为黄色。


我看到有人评论为什么我不使用CSS,这是一个小解释:我无法选择父元素。我只能使用parents()从子元素中进行操作。由于CSS尚未支持parents()方法,因此我选择了jQuery。:)


1
为什么不只使用CSS做这件事呢? - ibrahim mahrir
@ibrahimmahrir 在我的情况下,我没有办法仅仅通过父元素本身来选择它。我只能使用parents()从子元素中选择它,而且css目前还不支持这种方式。 - Rachel Nicolas
@RachelNicolas 如果您无法直接选择元素,那么肯定可以通过它们在DOM中的位置进行选择,例如 #container .panel > div。CSS绝对是这里的答案。此外,使用 hover() 然后检查 mouseenter 事件有点多余 - 只需使用 on('mouseenter', fn) 即可。 - Rory McCrossan
2个回答

2

仅使用CSS:

div {
  padding: 20px;
  border: 1px solid black;
}

/* something hovered that have .child as direct child => change .child color to blue */
*:hover > .child {
  background-color: blue;
}

/* .child element hovered => override the above color and set it to yellow (note that the above rule is still taking effect when this is taking effect) */
.child:hover {
  background-color: yellow;
}
<div>
  PARENT
  <div class="child">CHILD</div>
</div>
<div>
  PARENT
  <div class="child">CHILD</div>
</div>
<div>
  PARENT
  <div class="child">CHILD</div>
</div>


我完全忘记了 *:hover!它正好按照我的意愿工作!非常感谢你! - Rachel Nicolas

2
这是您期望的行为吗?

$('#child').parent().on('mouseover', function(e){
  if(this===e.target){
    $(this).children().css('background','blue');
  }else{
    $(this).children().css('background','yellow');
  }
}).on('mouseout', function(e){      
    $(this).children().css('background', 'green');
});
#parent{
  width:200px;
  height:100px;
  background-color:#f00;
}

#child{
  width:30px;
  height:30px;
  background-color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
  <div id="child"></div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接