CSS:更改子级div的背景颜色,但不更改父级div的背景颜色

时间:2018-10-02 07:50:03

标签: html css

我有一个具有三个子div的div。

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

这是我们需要的:

点击父级,父级div与background-color会获得不同的:active 点击一个孩子,孩子的div使用:active

获得不同的背景颜色。

问题:单击子级时,父级和子级都处于活动状态,并且都获得了不同的background-color

我尝试了:active:not(:matches(parent)),但是没有用。

如果没有Jquery,是否可以解决?如果可以,怎么办?

4 个答案:

答案 0 :(得分:0)

您可以使用:focustab-index更改背景

.child{
  padding: 5px;
}
.child:focus{
  background-color: green;
  color: #FFF;
}
<div class="parent">
  <div class="child" tabindex="1"> something </div>
  <div class="child" tabindex="2"> something </div>
  <div class="child" tabindex="3"> something </div>
</div>

答案 1 :(得分:0)

您需要使用stopPropagation(),它也不会将click事件传递给父级

$(".parent").click(function() {
  $(this).css("background-color", "#E1F3F7");
})

$(".child").click(function(event) {
  event.stopPropagation();
  $(this).css("background-color", "#E7F7E1");
})
.parent {
  background-color: #e5e5e5;
  padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <div class="child"> something </div>
  <div class="child"> something </div>
  <div class="child"> something </div>
</div>

答案 2 :(得分:0)

我解决了。

由于div上的单击本身已经由jquery处理,并且借助此处的一篇帖子(现在找不到),我设法解决了该问题。

单击div时,我在设置window.href之前在div中添加一个名为“ actief”的类。

$(this).addClass('actief');

然后在CSS中,我添加了此内容:

.parent.actief {
   background-color: red;
}
.child.actief {
   background-color: blue;
}

由于点击重定向到新页面,因此颜色仅设置了几毫秒。

感谢所有帮助和建议。

答案 3 :(得分:0)

如果您能够添加新的子元素,则可以尝试类似的操作。

.parent {
  position: relative;
  padding: 50px;
  background-color: grey;
}
.parent:active {
  background-color: red;
}
.child {
  position: relative;
  z-index: 2;
}
.child:active {
  background-color: blue;
}
.underlay {
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
  display: none;
  background-color: grey;
  z-index: 1;
}
.child:active ~ .underlay {
  display: flex;
}
<div class="parent">
  <div class="child"> something </div>
  <div class="child"> something </div>
  <div class="child"> something </div>
  <div class="underlay"></div>
</div>

小提琴

https://jsfiddle.net/Hastig/jsr9e7hd/

相关问题