jQuery - 获取与设置 CSS 类
使用 jQuery,可以很容易地操作元素的样式。
jQuery 操作 CSS
jQuery 有几种 CSS 操作方法。我们主要看以下方法:
addClass()- 将一个或多个样式类添加到选定元素中removeClass()- 从选定元素中删除一个或多个样式类toggleClass()- 在 添加/删除 元素的样式类之间切换css()- 设置或返回样式属性
实例样式表
以下样式表将用于本页上的所有示例:
.important {font-weight: bold;font-size: xx-large;}.blue {color: blue;}
jQuery addClass() 方法
下面的实例演示如何将样式类属性添加到不同的元素。当然,在添加样式类时,可以选择多个元素:
实例
<!DOCTYPE html><html><head><script src="https://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script><script>$(document).ready(function(){$("button").click(function(){$("h1, h2, p").addClass("blue");$("div").addClass("important");});});</script><style>.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>给元素加上样式类</button></body></html>
还可以在 addClass() 方法中指定多个样式类:
实例
<!DOCTYPE html><html><head><script src="https://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script><script>$(document).ready(function(){$("button").click(function(){$("#div1").addClass("important blue");});});</script><style>.important {font-weight: bold;font-size: xx-large;}.blue {color: blue;}</style></head><body><div id="div1">这是一些文本</div><div id="div2">这是一些文本</div><br><button>向第一个 div 元素添加样式类</button></body></html>
jQuery removeClass() 方法
下面的实例演示如何从不同的元素中删除特定的样式类属性:
实例
<!DOCTYPE html><html><head><script src="https://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script><script>$(document).ready(function(){$("button").click(function(){$("h1, h2, p").removeClass("blue");});});</script><style>.blue {color: blue;}</style></head><body><h1 class="blue">标题 1</h1><h2 class="blue">标题 2</h2><p class="blue">这是一个段落</p><p>这是另一个段落</p><button>从元素中删除样式类</button></body></html>
jQuery toggleClass() 方法
下面的实例将演示如何使用 jQuery toggleClass() 方法。此方法在 添加/删除 选定元素的类之间切换:
实例
<!DOCTYPE html><html><head><script src="https://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script><script>$(document).ready(function(){$("button").click(function(){$("h1, h2, p").toggleClass("blue");});});</script><style>.blue {color: blue;}</style></head><body><h1 class="blue">标题 1</h1><h2 class="blue">标题 2</h2><p class="blue">这是一个段落</p><p>这是另一个段落</p><button>切换 class</button></body></html>
jQuery css() 方法
jQuery css() 方法将在下一章中讲解。
jQuery HTML 参考
有关所有 jQuery HTML 方法的完整概述,请访问本站的 jQuery HTML/CSS 参考。