javascript - 悬停父div时,更改子div的背景色

标签 javascript jquery html css this

我有以下设置:

<div class="parent">
  <div class="child">
  </div>
  <div class="child">
  </div>
  <div class="child">
  </div>
</div>

当鼠标悬停在其中任何一个上时,我试图同时更改所有这些的所有背景颜色。我试过:

<script type="text/javascript">
 $(function() {
    $('.parent').hover( function(){
       $(this).css('background-color', 'gray');
    },
     function(){
      $(this).css('background-color', 'red');
    });
 });
 </script>

但是,颜色并没有“透过” children 看出来<div>秒。

有没有办法选择“this”的后代。我连续有很多这样的集合,所以我想我需要使用“this”,所以我没有通过 id 调用每个父项。我在想这样的事情:

<script type="text/javascript">
 $(function() {
    $('.parent').hover( function(){
       $(this "div").css('background-color', 'gray');
    },
     function(){
      $(this "div").css('background-color', 'red');
    });
 });
 </script>

但是,不能让它正常工作——jquery.com 上的所有示例都使用 id 选择器……没有一个使用“this”。

非常感谢!

最佳答案

如果您的目标不是 IE6,则无需使用 JavaScript,纯 CSS 即可:

.parent, .child {
    background-color:red;
}

.parent:hover, .parent:hover .child {
    background-color:gray;
}

关于javascript - 悬停父div时,更改子div的背景色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5135498/

相关文章:

javascript - 使用 Moment 获取 Date 对象的月份

javascript - 在jQuery中,如何将多个delay()方法与css()一起使用?

html - 对齐 self : flex-end breaks on mobile zoom

php - 在 Javascript 中循环遍历 JSON 数组

javascript - 使用 tweendash 制作动画的曲线 d3 线

Javascript 将数组中的嵌套对象转换为数组

html - Mailx 发送 html 消息

html - 是否可以使 div 背景具有不透明度但具有渐变的某些像素边界?

javascript - 如何在 TypeScript 中为图像添加路径别名?

jquery columnizer 和显示 :none