jQuery 操作 CSS
jQuery 拥有若干进行 CSS 操作的方法。我们将学习下面这些:
- addClass() - 向被选元素添加一个或多个类
- removeClass() - 从被选元素删除一个或多个类
- toggleClass() - 对被选元素进行添加/删除类的切换操作
- css() - 设置或返回样式属性
$(document).ready(function(){ $("button").click(function(){ $("h1,h2,p").addClass("blue"); $("div").addClass("important"); }); }); </script> <style type="text/css"> .important { font-weight:bold; font-size:xx-large; } .blue { color:blue; } </style> </head> <body> <h1>标题 1</h1> <h2>标题 2</h2> <p>这是一个段落。</p> <p>这是另外一个段落。</p> <div>这是一些重要的文本!</div> <br> <button>为元素添加 class</button>
在 addClass() 方法中规定多个类:
<script> $(document).ready(function(){ $("button").click(function(){ $("body div:first").addClass("important blue"); }); }); </script> <style type="text/css"> .important { font-weight:bold; font-size:xx-large; } .blue { color:blue; } </style> </head> <body> <div id="div1">这是一些文本。</div> <div id="div2">这是一些文本。</div> <br> <button>按钮</button>
jQuery removeClass() 方法
下面的例子演示如何在不同的元素中删除指定的 class 属性:
<script> $(document).ready(function(){ $("button").click(function(){ $("h1,h2,p").removeClass("blue"); }); }); </script> <style type="text/css"> .blue { color:blue; } </style> </head> <body> <h1 class="blue">标题 1</h1> <h2 class="blue">标题 2</h2> <p class="blue">这是一个段落。</p> <button>从元素中移除 class</button>
jQuery toggleClass() 方法
下面的例子将展示如何使用 jQuery toggleClass() 方法。该方法对被选元素进行添加/删除类的切换操作
<script> $(document).ready(function(){ $("button").click(function(){ $("h1,h2,p").toggleClass("blue"); }); }); </script> <style type="text/css"> .blue { color:red; } </style> </head> <body> <h1 class="blue">岛在海深处</h1> <h2 class="blue">你在我心里</h2> <p class="blue">全世界最好的你</p> <p>可是我只是从你的全世界路过</p> <br> <button>给你小心心</button>
----------------------------------------------------------------------------------------------------------------
设置 CSS 属性
如需设置指定的 CSS 属性,请使用如下语法:
css("
propertyname","
value");
$(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 元素的 background-color </button>设置多个css样式的时候需要通过{ }隔开 通过,连接