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");
});

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.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>为元素添加 class</button>

</body>
</html>

运行前

image.png

运行后

image.png

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

例如同时添加:"important blue"样式

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

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://cdn.bootcss.com/jquery/1.10.2/jquery.min.js">
</script>
<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>为第一个 div 元素添加类</button>

</body>
</html>

运行前

image.png

运行后

image.png

如何在不同的元素中删除指定的 class 属性:

使用jQuery removeClass()

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

如何对被选元素进行添加/删除类的切换操作

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 通过jQuery,您可以选取(查询,query)HTML元素,并对它们执行“操作”(actions)。 jQuer...
    枇杷树8824阅读 671评论 0 3
  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 13,815评论 1 92
  • 一、样式篇 第1章 初识jQuery (1)环境搭建 进入官方网站获取最新的版本 http://jquery.co...
    凛0_0阅读 3,467评论 0 44
  • 第一章 jQuery简介 1-1 jQuery简介 1.简介 2.优势 3.特性与工具方法 1-2 环境搭建 进入...
    mo默22阅读 1,623评论 0 11
  • importUIKit classViewController:UIViewController{ // iOS显...
    冰凡513阅读 134评论 0 0