如何通过检查css属性的特定类名来将css属性添加到元素的伪类中

时间:2017-07-29 10:48:07

标签: javascript css css3 css-selectors

<div class="header">
<span class= "text">
  <span class="icon disable">
  ::before
  </span>
<span>
  ::after
</div>

我想通过检查其子跨距是否具有类名“禁用”来添加css属性background:透明到psuedo class :: after of span with class name“text”。

请查看图片,了解我的要求,为我提供任何解决方案。有可能在css中做到吗?

我试了好几个小时..拜托,帮帮我吧! 提前致谢.......... described in image

2 个答案:

答案 0 :(得分:0)

这不是那么简单。但您可以使用jQuery hasClass()方法完成此操作。

HTML

<div class="header">
  <span class= "text">
    <span class="icon disable">
      Hai
    </span>
  <span>
</div>

JQuery的

if($('.icon').hasClass('disable')) {
  $('.text').addClass('disableChild')
}

CSS

.disableChild {
  background-color: red;
}

检查此链接 工作模型codepen

答案 1 :(得分:0)

if ($(".text").children().hasClass("disable")) {
  $(".text").addClass("child-disable");
}
.text.child-disable::after {
  background: transparent;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header">
  <span class="text">
    <span class="icon disable">
    </span>
  </span>
</div>

或者,如果页面上有多个元素,并且您希望对每个元素进行此操作,则可以使用以下内容:

$(".text").each(function(i, el) {
  var $this = $(el);
  if ($this.children().hasClass("disable")) {
    $this.addClass("child-disabled");
  }
});
.text.child-disabled::after {
  background: transparent;
}

.header {
  background-color: #f5f5f5;
  width: 95%;
  margin: 12px auto;
}

.icon {
  display: block;
  text-align: center;
}

.icon:not(.disable) {
  color: red;
}

.text::after {
  content: "";
  width: 100%;
  display: block;
  height: 4px;
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="header">
  <span class="text">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. </p>
    <span class="icon disable">
    &hearts;
    </span>
  </span>
</div>

<div class="header">
  <span class="text">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. </p>
    <span class="icon">
    &hearts;
    </span>
  </span>
</div>