
使用jquery添加css样式的方法:
css()方法添加css样式
addClass()方法添加css样式
1、使用css()方法设置css样式
css() 方法设置或返回被选元素的一个或多个样式属性。
如需返回指定的 CSS 属性的值,请使用如下语法:
css("propertyname");如需设置指定的 CSS 属性,请使用如下语法:
css("propertyname","value");示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
$(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 元素的背景色</button>
</body>
</html>效果图:

2、使用addClass() 方法添加css样式
addClass()方法向被选元素添加一个或多个类。该方法不会移除已存在的 class 属性,仅仅添加一个或多个 class 属性。
注:如需添加多个类,请使用空格分隔类名。
语法:
$(selector).addClass(class)
示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p:first").addClass("intro note");
});
});
</script>
<style>
.intro{
font-size:30px;
color:blue;
}
.note{
background-color:yellow;
}
</style>
</head>
<body>
<h1>这是一个标题</h1>
<p>这是一个段落。</p>
<p>这是另一个段落。</p>
<button>为第一个P元素添加两个类名</button>
</body>
</html>效果图:

以上就是jquery怎么加css样式?的详细内容,更多请关注易知道|edz.cc其它相关文章!














