在jquery中,可以使用addClass()方法或css()方法来添加css样式。
1、使用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 type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$("p:first").addClass("intro");
});
});
</script>
<style type="text/css">
.intro {
font-size: 120%;
color: red;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>向第一个 p 元素添加一个类</button>
</body>
</html>2、使用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>试试吧@







网友评论文明上网理性发言 已有0人参与
发表评论: