Removing an element added by ::before pseudo selector

断了今生、忘了曾经 提交于 2019-12-19 09:02:46

问题


I have the following case: (styling is done in SASS and unnecessary stylings are omitted.)

.header {
  ...
  &::before {
    ...
    position: absolute;
    height: 0.5rem;
    ...
  }
}

This creates a bar on top of the application's menu bar. In certain cases this bar has to be removed. I have read questions like these, but with no success. What would be the best way to remove this bar added by the ::before selector?


回答1:


Only CSS can remove pseudo element, so you need to have an other class that display:none; the before. First declare that class in the CSS :

.header {
  ...
  &::before {
    ...
    position: absolute;
    height: 0.5rem;
    ...
  }

  &.no-before::before{
    display:none;
  }
}

Then, when you want to remove it :

$('.header').addClass('no-before'); //Remove before
$('.header').removeClass('no-before'); //Re-add before



回答2:


The usual way is to create a more specific rule that applies to the element(s) in question (or a later rule with the same specificity), and specify display: none to hide the pseudo in that case.

For example: Here, I want to have an X in front of <span class="foo">, but not if they're in .header:

span.foo::before {
  content: 'X ';
}
.header span.foo::before {
  display: none;
}
<div>
  These have the X:
  <span class="foo">span.foo 1</span>
  <span class="foo">span.foo 2</span>
  <span class="foo">span.foo 3</span>
</div>
<div class="header">
  These don't:
  <span class="foo">span.foo 4</span>
  <span class="foo">span.foo 5</span>
  <span class="foo">span.foo 6</span>
</div>



回答3:


If you are manipulating the DOM by using JavaScript, you can add a class name - for instance .remove-bar - to the element having .header in order to remove the pseudo-element (generated content):

.remove-bar {
    &::before { content: none; }
}

Also make sure that it is placed after the previous styles, or use a more specific selector if needed.



来源:https://stackoverflow.com/questions/28608023/removing-an-element-added-by-before-pseudo-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!