jquery can add css style. Method: 1. Use css() to set the style attribute of the matching element. The syntax is "$(selector).css(attribute name, attribute value)"; 2. Use attr(), the syntax is "$(selector).attr("style","style code")".
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
jquery can add css styles. For example, you can use the css() method to add CSS styles, or use the attr() method to add css inline styles by setting the style attribute.
How to add css style with jquery
1. Use css()
css( ) method returns or sets one or more style properties of the matched element.
Syntax for setting css styles
$(selector).css(name,value)
Parameters | Description |
---|---|
name | Required. Specifies the name of the CSS property. This parameter can contain any CSS property, such as "color". |
value | Optional. Specifies the value of a CSS property. This parameter can contain any CSS property value, such as "red". If the empty string value is set, removes the specified attribute from the element. |
Example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script src="js/jquery-1.10.2.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { $("p").css("color", "red"); }); }); </script> </head> <body> <p>这是一个段落</p> <p>这是另一个段落</p> <button>改变段落的颜色</button> </body> </html>
##2. Use attr()
attr() method sets or returns the attribute value of the selected element. When you use the attr() method to set the style attribute of an element, you can add a css style to the element.<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script src="js/jquery-1.10.2.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { // $("div").attr({"style":"border: 5px solid paleturquoise;"}); $("div").attr("style", "border: 5px solid paleturquoise;width: 200px;"); }); }); </script> </head> <body> <div>hello</div> <br> <button>给div元素添加css样式</button> </body> </html>
jQuery video tutorial, web front-end introductory video]
The above is the detailed content of Can jquery add css styles?. For more information, please follow other related articles on the PHP Chinese website!