jQuery - 获取并设置 CSS 类

Posted 司会铭

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jQuery - 获取并设置 CSS 类相关的知识,希望对你有一定的参考价值。

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


 

jQuery 操作 CSS

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

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

 

实例样式表

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

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

.blue
{
color:blue;
}

jQuery addClass() 方法

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

实例

技术分享
<!DOCTYPE html>
<html>
<head>
<script src="/jquery/jquery-1.11.1.min.js"></script>
<script>
$(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>向元素添加类</button>

</body>
</html>
View Code

查看结果:

技术分享      技术分享

 

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

实例

技术分享
<!DOCTYPE html>
<html>
<head>
<script src="/jquery/jquery-1.11.1.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").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>向第一个 div 元素添加类</button>

</body>
</html>
View Code

查看结果:

技术分享        技术分享


 

jQuery removeClass() 方法

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

实例

技术分享
<!DOCTYPE html>
<html>
<head>
<script src="/jquery/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("h1,h2,p").removeClass("blue");
  });
});
</script>
<style type="text/css">
.important
{
font-weight:bold;
font-size:xx-large;
}
.blue
{
color:blue;
}
</style>
</head>
<body>

<h1 class="blue">标题 1</h1>
<h2 class="blue">标题 2</h2>
<p class="blue">这是一个段落。</p>
<p>这是另一个段落。</p>
<br>
<button>从元素上删除类</button>
</body>
</html>
View Code

查看结果:

技术分享          技术分享

 


 

 

jQuery toggleClass() 方法

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

实例

技术分享
<!DOCTYPE html>
<html>
<head>
<script src="/jquery/jquery-1.11.1.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("h1,h2,p").toggleClass("blue");
  });
});
</script>
<style type="text/css">
.blue
{
color:blue;
}
</style>
</head>
<body>

<h1>标题 1</h1>
<h2>标题 2</h2>
<p>这是一个段落。</p>
<p>这是另一个段落。</p>
<button>切换 CSS 类</button>
</body>
</html>
View Code

查看结果:

 

技术分享                技术分享

 


 

以上是关于jQuery - 获取并设置 CSS 类的主要内容,如果未能解决你的问题,请参考以下文章

jQuery - 获取并设置 CSS 类

jQuery - 获取并设置 CSS 类

第二十五篇 jQuery 学习7 获取并设置 CSS 类

jQueryjQuery HTMLtext()html()attr()prop ()添加删除元素不同方法创建元素获取并设置 CSS 类尺寸

jquer 事件,选择器,dom操作

jQuery 学习03——HTML:捕获设置添加元素删除元素CSS类CSS()方法尺寸