Two ways to add: 1. Use css() to set one or more style attributes, the syntax is "element object.css({attribute: value, attribute: value,...})". 2. Use addClass() to add the defined style class, the syntax is "element object.addClass("class name")". If you need to add multiple classes, separate the class names with spaces.
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
If you want to add styles using jquery, you can:
Use css() to set one or more style attributes
Use addClass() to add multiple defined style classes
1. Use the css()
css() method to select the selected element. Set one or more style properties.
$(selector).css({属性:值,属性:值,...})
Example 1:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <style> .siblings * { display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } </style> <script> $(document).ready(function() { $("button").click(function() { $("p").css({ "color": "white", "background-color": "#98bf21", "font-family": "Arial", "font-size": "20px", "padding": "5px" }); }); }); </script> </head> <body> <button>给P元素添加多个样式</button> <p>这是一个段落。</p> <p>这是另一个段落。</p> </body> </html>
It can be seen that the font color style, background color style, font size style, and padding are added style.
2. Use the addClass()
addClass() method to add one or more class names to the selected element.
This method does not remove the existing class attribute, but only adds one or more class names to the class attribute.
$(selector).addClass("类名")
Tip: If you need to add multiple classes, please use spaces to separate class names.
Example 2:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <style> .siblings * { display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } </style> <script> $(document).ready(function() { $("button").click(function() { $("p").addClass("intro note"); }); }); </script> <style> .intro { font-size: 30px; color: blue; } .note { background-color: yellow; } </style> </head> <body> <button>给P元素添加多个样式</button> <p>这是一个段落。</p> <p>这是另一个段落。</p> </body> </html>
[Recommended learning: jQuery video tutorial, web front-end development]
The above is the detailed content of How to add style in jquery. For more information, please follow other related articles on the PHP Chinese website!