Although the title is written 伪元素
, but this article is mainly said ::before
and ::after
, the remaining several pseudo-elements ( ::first-letter
,, ::first-line
, ::selection
etc.) because there is no content
attribute, so this article a stroke, in fact, the method is the same.
Pseudo elements focus on a pseudo , although they can be recognized by the browser rendering engine and render correctly, but the pseudo-element itself is not DOM elements, so can not be directly manipulated by JS-- Therefore any CSS change method that directly selects DOM elements based on JS has no effect on pseudo-elements. (JQ seems omnipotent, this problem is directly planted.) Since JQ's selectors are based on DOM elements) about JS and JQ selectors, you can refer to these two documents: selectors API Level 1, JQuery selectors
Get property values for pseudo-elements
Although JS does not have the option to manipulate pseudo-elements directly, there are ways to get its CSS properties.
window.getComputedStyle
Use the window.getComputedStyle
method to select the pseudo-element, and then use the getPropertyValue
method to get the value of the corresponding property.
Based on the documentation for the MDN,
window.getComputedStyle(element[, pseudoElt]);
This method contains two parameters, one is the element itself and the other is the pseudo-element of the element.
JS Syntax Example (full demo online link):
var div=document.querySelector(‘div‘);var fontSize=window.getComputedStyle(div,‘::before‘).getPropertyValue(‘font-size‘);//获取before伪元素的字号大小
You can refer to this article for an explanation of this method:
Get the getComputedStyle method of element CSS value familiar
Change the property value of a pseudo-element
window.getComputedStyle
Although the method can get the property value of the pseudo-element, but according to the method name also know that it can only get CSS style, and can not change the CSS properties, then if you want to change the value of pseudo-element property with JS, how to deal with it?
There are several ways to do this:
JS changing data-*
The value of a property to change the value of a pseudo-element content
Create multiple class
, switch class
to achieve the purpose of changing the style
Add styles using Cssstylesheet's insertRule
method
Overlay external CSS with high priority for internal CSS styles
The recommended degree of implementation of the above is decreasing in turn
Using the DOM's
data-*
property to change
content
The value
data-*
HTML5 is a new DOM element attribute that can be roughly understood as a tag. For specific usage, refer to this article for MDN. content
There is a special way to obtain the attribute value of a pseudo-element in addition to the regular assignment attr()
.
Html:
<div class="test" data-text="TEXT" data-color="red"></div>
Css:
.test::before{ content: attr(data-text);}
Results:
TEXT
In content
fact, can be more than attr ligatures, and attr () can be any of the DOM elements of the attributes (such as class
, and even non-standard properties are supported, but not recommended) so it is convenient to make up some template text. It is perfectly fine to do the following. Note Use a space to connect, do not use the "+" sign.
EXAM:
.test::before { content: ‘我的类是‘ attr(class) ‘想要变成‘ attr(data-color);}
Although the attr()
Internet is endowed with infinite possibilities, including color
, and so on, properties that are expected to width
change in the future, however, only content
support this method , the rest are draft state, there is no browser support. The only reason to put this in the first place is because it's really too simple and elegant compared to other implementations.
But what if you really want to change the elements in a pseudo-element color
?
Change
class
To implement a pseudo-element style change
Put this method to the recommendation bit the second estimate will be a lot of people scold me: "Crouching trough, so simple and not forcing the way you actually put the second!" Too little level. " However, you may have a better idea of the following two ways.
The advantage of this method is that it is easy to use and has no compatibility issues. The disadvantage is that some of the more useful class
, much like the jquery class selector poisoning patients, the other is not suitable for multi-state scenes (such as real-time changes in pseudo-element text size, etc.).
The implementation is too simple to stick to the code.
The front class切换大法
may feel unpleasant, here to a tall (pseudo) point method:
Using Cssstylesheet's
insertRule
method to add a style
This part of the content and the standard of the more popular, coupled with more unpopular, not many people pay attention to, the individual currently gnawing standard, so this part of the content will not do in-depth analysis, understanding may also have problems, hope treatise.
Cssstylesheet is the object method that the browser holds all the CSS stylesheets in the page (excluding inline styles), link
and each and every style
tag represents a Cssstylesheet object that gets the method that they can use document.styleSheets
. (It is important to note that although the results returned by the method are included in the styleSheets
link
external style of the label introduction, the non-IE browser is not able to get their cssRules
attributes, only the style
elements within the embedded tag can be obtained)
document.styleSheets[0].insertRule(‘.test::before{color:green}‘,0)//chrome,firefox等非IE浏览器使用document.styleSheets[0].addRule(‘.test::before{color:green}‘,0)//IE系列浏览器使用/* 虽然部分浏览器也可以通过id来指定,‘document.styleSheets.id.insertRule()‘这种写法在chrome和IE下都行得通,但是firefox会返回‘undefined‘,所以建议还是使用index值来获取stylesheet */
.insertRule
The syntax is stylesheet.insertRule(rule, index)
that the other argument is that the position of the style sheet in the corresponding stylesheets, the larger the value, the higher the index
cssRules
style priority, but the value cannot exceed the current style sheet rule ( cssRules
) Length (the style defined in the CSS will always be overwritten by the later definition.) ), when the value is less than the cssRules
length, the added style rule is inserted into the position where the index
values are defined, and the remaining rules are postponed sequentially.
addrule
And the insertRule
method is essentially no difference, but the latter is not recognized by IE browser, so the former as a browser-compatible method exists. (The following is a way to insertRule
refer to these two methods in the form of space savings.) )
The code above looks like a simple line, but it doesn't work every time. There are several reasons for this:
document.styleSheets
Although the style
corresponding is returned in the order of and, the link
StyleSheetList
first one if it is instead of, the preceding is not link
able to style
get the corresponding at this time, cssRules
then document.styleSheets[0].cssRules
, the null
insertRule
method does not work. (This situation is only for non-IE browser, ie browser is normal, but the definition of the early often means to be covered by the following style, so the meaning is not very significant)
As above, the method does not work if there are no inline style labels in the page style
insertRule
.
index
If the value is not large enough, it is likely that the CSS file will be positioned earlier than the beginning of the definition, causing it to be overwritten. So there is a tradeoff that adds to the added style !important
, although I personally resent it.
This shows the limitations of this approach, but the elegance of this approach is to avoid writing inline styles directly, but using CSS APIs to make changes. It's a little bit better than the following method.
But this method seems to be a bit too restrictive?
HEAD
Added in
style
Tags force override initial properties
This method uses the high priority of the internal CSS style to cover the external CSS, the benefits are simple and easy to understand, easy to implement. The disadvantage is that eating is too ugly, too rough.
var style=document.createElement(‘style‘);style.innerHTML=".test::before{color:green}";//添加样式内容的话也可以用上面提到过的`insertRule`,相对例子里的硬编码会更优雅点。document.head.appendChild(style);
See here may be some people reflect, in fact style
tagging this method can be insertRule
the premise of the implementation of the method-because not all of the beginning of the page has embedded style
style. This method is not very good, but sometimes it is really necessary-for example, "Drag the slider to change the size of pseudo-element text" this requirement.
Reprinted: 1190000003711146
Using JavaScript to get and modify the values of pseudo-elements