How do I read and write pseudo-class Element styles ?, Read/write pseudo element styles
Example:
Html code
- <P class = "example" data-pseudo = "(I'm content.)"> Hi, this is a plain-old, sad-looking paragraph tag. </p>
- <Div id = "log"> </div>
- <Style>
- . Example: before {
- Content: 'false ';
- Color: red;
- }
- </Style>
1. Read data using the window. getComputedStyle method:
Js Code
- <Script>
- Var str = window. getComputedStyle (document. querySelector ('. example'), ': before'). getPropertyValue ('color ');
- Document. querySelector ('# log'). innerHTML = str;
- </Script>
Ii. Write (modify)
No way. At least there is no direct method, and we can only achieve our goal by overwriting the style.
For example, add a style element and write a new style, or add different classes to the target element to achieve the control effect.
Example:
Html code
- <Style id = "pseudo dostyle">
- </Style>
Js Code
- <Script>
- Document. querySelector ('# pseudo style'). sheet. insertRule (". example: before {color: green;}", 0 );
- // Or
- Document. querySelector ('# pseudostyle'). sheet. addRule ('. example: before ', 'color: green ');
- // SetProperty will throw an exception at this time:
- Try {
- Window. getComputedStyle (document. querySelector ('. example'), ': before'). setProperty ('color', "green ");
- } Catch (e ){
- Document. querySelector ('# log'). innerHTML = e;
- }
- </Script>
A pseudo-class element has a special attribute: content. Because its value can be defined to be obtained from the dom attribute of the element, it can implement direct reading and writing of js.
For example:
Html code
- <Style>
- . Example: before {
- Content: attr (data-pseudo );
- Color: red;
- }
- </Style>
Js Code
- <Script>
- Document. querySelector ('. example'). setAttribute ("data-pseudo", "new content! ");
- </Script>
Appendix:
1. styleSheet object method, attributes and browser compatibility, refer to: http://help.dottoro.com/ljpatulu.php
2. getComputedStyle method, reference: http://help.dottoro.com/ljscsoax.php, https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle