During development, we often encounter the need to dynamically modify the CSS style effect of an element, or dynamically change the style name of its div, next, I will introduce the implementation methods of js and jquery.
The js operation is simple. You can directly operate document. getElementById (id ).
Example
The Code is as follows: |
Copy code |
<! DOCTYPE html> <Html> <Head> <Title> TITLE </title> <Style type = "text/css"> # MyDiv { Background-color: blue; Width: 100px; Height: 200px; } </Style> <Script type = "text/javascript"> Window. onload = function (){ Alert (document. getElementById ("myDiv"). style. width ); Document. getElementById ("myDiv"). style. width = "100px "; } </Script> </Head> <Body> <Div id = "myDiv" style = "background-color: red; border: 1px solid black"> MyDiv </Div> </Body> </Html> |
Jquery Operation Method
The Code is as follows: |
Copy code |
<P class = "myclass" title = "select your favorite fruit"> what is your favorite fruit? <P>
|
In the code above, the class is also the attribute of the p element. Therefore, you can use the attr () method to obtain the class and set the class.
The Code is as follows:
The Code is as follows: |
Copy code |
Var p_class = $ ("p"). attr ("class"); // obtain the class of the p element
|
You can also use the attr () method to set the class.
The Code is as follows: |
Copy code |
$ ("P"). attr ("class", "high"); // set the class of the p element to high
|
In most cases, it replaces the original class with the new class, instead of appending the new class on the basis of the original
The new Code is
The Code is as follows: |
Copy code |
<P class = "high" title = "select your favorite fruit"> what is your favorite fruit? <P>
|
Append Style
The Code is as follows: |
Copy code |
<Style> . Another { Font-style: italic;/* italic */ Color: blue;}/* set the font to blue */ </Style> |
Append a style to the webpage
The Code is as follows: |
Copy code |
$ ("Input: eq (2)"). click (function (){ $ ("P"). addclass ("another "); }) |
The removeClass () method is used to remove a style.
The Code is as follows: |
Copy code |
$ ("P"). removeclass ("high "); <P class = "high another"> test <p>, |
Remove both p classes
The Code is as follows: |
Copy code |
$ ("P"). removeclass ("high"). removeclass ("another "); Or $ ("P"). removeclass ("high another "); Or remove all classes. $ ("P"). removeclass ();
|
Change style
Jquery provides the toggleclass () method to control style switching.
The Code is as follows: |
Copy code |
$ ("P"). toggleclass ("another ");
|
Determines whether a style is included. If yes, true is returned. Otherwise, false is returned.
The Code is as follows: |
Copy code |
$ ("P"). hasClass ("another"); equivalent to $ ("p"). is (". another "); |