jQuery - 获取并设置 CSS 类

jQuery 教程 · 2019-03-09 12:13:48

通过 jQuery,可以很容易地对 CSS 元素进行操作。

jQuery 操作 CSS

jQuery 拥有若干进行 CSS 操作的方法。我们将学习下面这些:

  • addClass() - 向被选元素添加一个或多个类
  • removeClass() - 从被选元素删除一个或多个类
  • toggleClass() - 对被选元素进行添加/删除类的切换操作
  • css() - 设置或返回样式属性

实例样式表

下面的样式表将用于本页的所有例子:

.important { font-weight:bold; font-size:xx-large; } .blue { color:blue; }

jQuery addClass() 方法

下面的例子展示如何向不同的元素添加 class 属性。当然,在添加类时,您也可以选取多个元素:

实例

$("button").click(function(){ $("h1,h2,p").addClass("blue"); $("div").addClass("important"); });

您也可以在 addClass() 方法中规定多个类:

实例

$("button").click(function(){ $("body div:first").addClass("important blue"); });

jQuery removeClass() 方法

下面的例子演示如何在不同的元素中删除指定的 class 属性:

实例

$("button").click(function(){ $("h1,h2,p").removeClass("blue"); });

jQuery toggleClass() 方法

下面的例子将展示如何使用 jQuery toggleClass() 方法。该方法对被选元素进行添加/删除类的切换操作:

实例

$("button").click(function(){ $("h1,h2,p").toggleClass("blue"); });

jQuery css() 方法

我们将在下一章讲解 jQuery css() 方法。

点击查看所有 jQuery 教程 文章: https://www.codercto.com/courses/l/35.html

查看所有标签

Web Standards Creativity

Web Standards Creativity

Andy Budd、Dan Rubin、Jeff Croft、Cameron Adams、Ethan Marcotte、Andy Clarke、Ian Lloyd、Mark Boulton、Rob Weychert、Simon Collison、Derek Featherstone / friends of ED / March 19, 2007 / $49.99

Book Description * Be inspired by 10 web design lessons from 10 of the world's best web designers * Get creative with cutting-edge XHTML, CSS, and DOM scripting techniques * Learn breathtakin......一起来看看 《Web Standards Creativity》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

SHA 加密
SHA 加密

SHA 加密工具