Home >Web Front-end >JS Tutorial >How to add css style in jquery
How to add css style in jquery: 1. Use addClass() method to add css style, syntax such as "$(selector).addClass(class)"; 2. Use css() method to set css style, syntax Such as "css("propertyname")".
The operating environment of this article: windows7 system, jquery version 1.2.6, Dell G3 computer.
When using jquery, we often need to dynamically add CSS styles to some dom elements. Let's take a look at how Jquery dynamically adds css styles.
How to add css style with jquery:
Use addClass() method to add css style.
Use the css() method to set the css style.
1. Use the addClass() method to add css styles
The addClass() method adds one or more classes to the selected element. This method does not remove existing class attributes, it only adds one or more class attributes.
Note: If you need to add multiple classes, please use spaces to separate class names.
Grammar:
$(selector).addClass(class)
Example:
<html> <head> <script type="text/javascript" src="/jquery/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("p:first").addClass("intro"); }); }); </script> <style type="text/css"> .intro { font-size:120%; color:red; } </style> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <button>向第一个 p 元素添加一个类</button> </body> </html>
[Recommended learning: jquery video tutorial]
2. Use css() Method to set css style
css() method sets or returns one or more style attributes of the selected element.
To return the value of the specified CSS property, please use the following syntax:
css("propertyname");
To set the specified CSS property, please use the following syntax:
css("propertyname","value");
Example:
<!DOCTYPE html> <html> <head> <script src="/jquery/jquery-1.11.1.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").css("background-color","yellow"); }); }); </script> </head> <body> <h2>这是标题</h2> <p style="background-color:#ff0000">这是一个段落。</p> <p style="background-color:#00ff00">这是一个段落。</p> <p style="background-color:#0000ff">这是一个段落。</p> <p>这是一个段落。</p> <button>设置 p 元素的背景色</button> </body> </html>
The above is the detailed content of How to add css style in jquery. For more information, please follow other related articles on the PHP Chinese website!