You can add styles with jquery. Method: 1. Use the "$(element).attr("style","inline style code")" statement; 2. Use "$(element).css({ "Attribute name":"Attribute value"})" statement; 3. Use the "$(element).addClass("class name")" statement.
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
In jquery, there are many ways to add styles to elements. Here are a few:
Method 1: Use the attr() method to add inline styles
<!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(){ $("p").attr("style","border: 2px solid green; background-color: #55aa7f;color: white;"); }); }); </script> </head> <body> <p>hello,测试文字</p> <button>添加样式</button> </body> </html>
Method 2: Use the css() method
css() method to return or set one or more styles of the matching element Attributes.
<!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(){ $("p").css({"border": "1px solid red","background-color": "#FFC0CB","color": "white"}); }); }); </script> </head> <body> <p>hello,测试文字</p> <button>添加样式</button> </body> </html>
Method 3: Use the addClass method
addClass() method to add one or more classes to the selected 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(){ $("p").addClass("intro"); }); }); </script> <style type="text/css"> .intro { font-size: 120%; color: red; } </style> </head> <body> <p>hello,测试文字</p> <button>添加样式</button> </body> </html>
Recommended related video tutorials: jQuery Tutorial (Video)
The above is the detailed content of Can I add styles using jquery?. For more information, please follow other related articles on the PHP Chinese website!