Change the :before selector from javascript [duplicate]

会有一股神秘感。 提交于 2019-11-28 01:56:20

问题


How to change the :before content of #abc style from javascript ?

<script>
document.getElementById('abc').style.content='-';
</script>

<style>
#abc:before{content:"+";}
</style>

回答1:


No, you cannot access :before or :after from javascript, because they are not a part of the DOM. However you can still achieve your goal by using CSS classes:

<script>
    document.getElementById('abc').className = "minus";
</script>

<style>
    #abc:before {content: "+";}
    #abc.minus:before {content: "-"}
</style>

In fact this approach is more unobtrusive, because you don't mix representation with javascript. Tomorrow you might want to change text "+/-" to say nice background images, in this case you don't have to touch javascript code at all.




回答2:


As far as I know you cannot change the before since it is a pseudo element and not part of the DOM. What you can do is maybe add another class with javascript that has a seperate before specification.

Please see if this question can help you do a work-around Changing width property of a :before css selector using JQuery




回答3:


jQuery cannot set css properties on :before content, since it is not contained in an element. If you want to be able to manipulate the color of the :before content with javascript, you can create an extra css class, and add/remove this class.




回答4:


So update #abc to

#abc {
content: attr(data-before);
}

and ensure that the element that #abc refers to has a data attribute e.g

Then in your js, you can access the data-before attribute using the HTML data API and as you modify that, the content will change too.

Does that make sense?



来源:https://stackoverflow.com/questions/22659170/change-the-before-selector-from-javascript

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