How does jquery determine whether an element has a specified style?

Source: Internet
Author: User

There are two scenarios:
1. If css is written as an in-row style, you can determine it by obtaining the value of the style attribute, for example:
Determine whether the div element with id divid has a font-size style:
Copy codeThe Code is as follows:
<Div id = "divid" style = "float: left; font-size: 12px;"> </div>
The jquery code is as follows:
JQuery ("# divid"). each (function (){
Var fontSize = $ (this). attr ("style"). indexOf ("font-size ");
If (fontSize! = (-1) {alert ("defined ");}
Else{((this).css ({"float": "left", "font-size": "12px "});}
});

Note: if there is only one div element whose id is divid, jquery's each is executed only once.
2. If css is written as a class style, you can determine it by obtaining the value of the class attribute, for example:
Determine whether the div element with the id divid contains the class style divclass:
Copy codeThe Code is as follows:
. Divclass {
Background-color: # F33;
}
<Div id = "divid" class = "divclass"> </div>

The jquery code is as follows:
Copy codeThe Code is as follows:
JQuery ("# divid"). click (function (){
If (jQuery (this). attr ("class"). indexOf ("divclass")> 0 ){
JQuery (this). removeClass ("divclass ")
} Else {
JQuery (this). addClass ("divclass ")
}
});

Note: The above Code allows you to click to switch the background color.

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.