JS control pseudo Element Method summary _javascript Skill

Source: Internet
Author: User

I. Reason:

This article originated in the OSC community, where someone asked how to use JQ to get pseudo elements. My first thought is that the powerful CSS query should be able to get pseudo elements.

In fact, however, CSS query does not. That is, we cannot go through $ (": Before"), $ (DOM). Find (": Before") or Document.queryselector (": Before") to get: before pseudo element.

To do that, I had to get a new look at pseudo elements (pseudo-elements). Why not use JS directly to get pseudo element?

For example:: Before and:: After pseudo elements, used to insert content into the head or tail of elements in CSS rendering, they are not subject to document constraints, and do not affect the document itself, only affect the final style. These additions do not appear in the DOM, but are simply added to the CSS rendering layer.

In fact, pseudo elements can be rendered by the browser, but they are not DOM elements. It does not exist in the document, so JS cannot manipulate it directly. The jquery selector is based on DOM elements, and therefore does not directly manipulate pseudo elements.

So how do you manipulate the pattern of pseudo elements?

To this end, I decided to make a good summary of JS control pseudo element method, easy to check later.

Two. What are pseudo elements:

First, let's say a little bit about what the pseudo elements are. Pseudo elements have six, respectively:: After,:: Before,:: First-line,:: First-letter,:: Selection,:: Backdrop.

The most common pseudo elements in each major Web page are:: After and:: Before.

The semantics of these pseudo elements refer to my other article, "CSS pseudo-element selector summary."

In CSS3, it is recommended that pseudo elements use two colons (::) syntax, rather than a colon (:), to differentiate between pseudo and pseudo elements. Most browsers support both of these presentation syntaxes. Only:: Selection can always start with a two colon (::). Because IE8 only supports the syntax of a single colon, so if you want to be compatible with IE8, the insurance practice is to use a single colon.

Three. Get the attribute value of the pseudo element:

Get property values for pseudo elements you can use the window.getComputedStyle () method to get a CSS style declaration object for a pseudo element. The corresponding property values can then be obtained by using the GetPropertyValue method or by using the key-value access directly.

Syntax: window.getComputedStyle (element[, pseudoelement])

The parameters are as follows:

Element (Object): The DOM element in which the pseudo element is located;

Pseudoelement (String): pseudo element type. Optional values include: "After", ": Before", ": First-line", ": First-letter", ": Selection", ": Backdrop";

Give me a chestnut:

CSS code
#myId: before {
content: "Hello world!";
Display:block;
width:100px;
height:100px;
background:red;
}
HTML code
<div id= "myId" ></div>
//JS code
var myidelement = document.getElementById ("MyId");
var beforestyle = window.getComputedStyle (Myidelement, ": Before");
Console.log (Beforestyle); [Cssstyledeclaration Object]
console.log (beforestyle.width);//100px
Console.log ( Beforestyle.getpropertyvalue ("width")); 100px
Console.log (beforestyle.content);//"Hello world!"

Note:

1.getPropertyValue () and directly using key-value access, you can access cssstyledeclaration Object. The difference between them is:

For the Float property, you cannot use getComputedStyle (element, NULL) directly if you use a key value access. Float, but should be cssfloat and stylefloat;
Directly using the key value access, the property key needs to use the hump, such as: Style.backgroundcolor;
The GetPropertyValue () method does not have to be able to hump the writing form (not to support the hump), for example: Style.getpropertyvalue ("Border-top-color");
The GetPropertyValue () method is supported in ie9+ and other modern browsers, and in Ie6~8, the GetAttribute () method can be used instead;

2. Pseudo element default is "Display:inline". If you do not define the display property, even if the property value for width is set explicitly in the CSS as a fixed size such as "100px", the last width value is still "auto". This is because inline elements cannot be customized to set the width height. The solution is to modify the display property to "block", "Inline-block", or others for pseudo elements.

Four. Change the style of the pseudo element:

Method 1. Replace the class to implement the change of the pseudo element attribute value:

Give me a chestnut:

CSS code
. Red::before { 
content: "Red"; 
Color:red 
}
. Green::before { 
content: "Green"; 
Color:green;
}
HTML code
<div class= "Red" > Content content Content </div>
//jquery code
$ (". Red"). Removeclass (' Red '). AddClass (' green ');

Method 2. Use Cssstylesheet's insertrule to modify the style for pseudo elements:

Give me a chestnut:

Document.stylesheets[0].addrule ('. Red::before ', ' color:green '); Support IE Document.stylesheets[0].insertrule ('. Red::before {color:green} ', 0); Modern browsers that support non-IE

Method 3. Insert <style> internal style in

var style = document.createelement ("style"); 
Document.head.appendChild (style); 
sheet = Style.sheet; 
Sheet.addrule ('. Red::before ', ' color:green '); Compatible with IE browser
sheet.insertrule ('. Red::before {color:green} ', 0);//support for non-IE modern browsers

or use jquery:

$ (' <style>.red::before{color:green}</style> '). Appendto (' head ');

Five. Modify the attribute value of the content of the pseudo element:

Method 1. Use Cssstylesheet's insertrule to modify the style for pseudo elements:

var latestcontent = "Modified content";
var formercontent = window.getComputedStyle ($ ('. Red '), ':: Before '). GetPropertyValue (' content '); Document.stylesheets[0].addrule ('. Red::before ', ' content: ' + latestcontent + ' "); Document.stylesheets[0].insertrule ('. Red::before {content: ' + latestcontent + ' "} ', 0);

Method 2. Use the Data-* property of the DOM element to change the value of the content:

CSS code
. Red::before {
content:attr (data-attr);
color:red;
}
HTML code
<div class= "Red" data-attr= "Red" > Content content Content </div>
//Jacascript code
$ ('. Red '). attr (' data-attr ', ' green ');

Six.: Before and: The common usage summary of after pseudo element:

1. Add content decorations to elements using the content attribute:

1) Add string:

Using quotation marks to include a string of strings will add a string to the element's content. Chestnuts:

A:after {content: "After Content";}

2 Use the attr () method to invoke the value of the property of the current element:

Chestnuts:

A:after {content:attr (href);}
A:after {content:attr (data-attr);}

3 Use the URL () method to refer to the multimedia file:

Chestnuts:

A::before {content:url (logo.png);}

4 Use the Counter () method to invoke the timer:

Chestnuts:

H:before {counter-increment:chapter cotent: "chapter" Counter (Chapter) "."}

2. Clear float:

. clear-fix {*overflow:hidden; *zoom:1}
. clear-fix:after {display:table; content: ""; width:0; Clear:both; }

3. Magical Effect:

CSS code
a {
position:relative;
Display:inline-block;
Text-decoration:none;
Color: #000;
font-size:32px;
padding:5px 10px;
}
A::before, A::after { 
content: "";
Transition:all 0.2s;
}
A::before { 
left:0;
}
a::after { 
right:0;
}
A:hover::before, A:hover::after { 
position:absolute;
}
A:hover::before {content: "\5b"; Left: -20px;}
A:hover::after {content: "\5d"; right: -20px;}
HTML code
<a href= "#" > I'm a hyperlink </a>

4. The realization of special shape:

To raise a chestnut: (e.g. a conversation bubble)

CSS code
. tooltip {
position:relative;
Display:inline-block;
padding:5px 10px;
Background: #80D4C8;
Tooltip:before {
content: "";
Display:block;
Position:absolute;
left:50%;
Margin-left: -5px;
Bottom: -5px;
width:0; 
height:0; 
border-left:5px solid transparent;
border-right:5px solid transparent;
border-top:5px solid #80D4C8;
}
HTML code
<div class= "tooltip" >i ' m a tooltip.</div>

: Before and: After pseudo elements combined with more CSS3 powerful features, but also to complete a lot of interesting special effects and hack, where the right to be a trigger.

Six. A little suggestion:

The content properties of pseudo elements are powerful and can be written to various strings and portions of multimedia files. But the content of the pseudo element exists only in the CSS rendering tree and does not exist in the real DOM. So for SEO optimization, it's best not to include document-related content in pseudo elements.

Modifying the style of pseudo elements suggests a way to modify the style by replacing the class. Because the other two ways of inserting the character code into JavaScript are cssstylesheet, it is not conducive to separating style from control, and string concatenation is error-prone.

Modifying the value of the content property of a pseudo element is recommended by using the Data-* property of the DOM.

The above is a small set to the introduction of JS control pseudo element Method Summary, I hope to help you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.