css() 方法设置或返回被选元素的一个或多个样式属性。
返回指定的 CSS 属性的值
例如:$("p").css("background-color");
返回首个匹配元素的 background-color 值。
设置指定的 CSS 属性
例如:$("p").css("background-color","yellow");
为所有匹配元素设置 background-color 值。
设置多个 CSS 属性
例如:$("p").css({"background-color":"yellow","font-size":"200%"});
为所有匹配元素设置 background-color 和 font-size值。
案例:
html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
li{
font-size: 20px;
}
</style>
<script src="jquery-3.3.1.min.js"></script>
<script src="jQuery1.js"></script>
</head>
<body>
<li>我是li元素</li>
<li>我是li元素</li>
<li>我是li元素</li>
<li>我是li元素</li>
</body>
</html>
js文件
$(document).ready(function () {
//获取样式的值
var a = $("li").css("font-size");
console.log(a);
//设置样式
$("li").css("background-color","yellow");
//设置多个样式,用一个大括号{},括起来
$("li").css({
"color": "white",
"font-size": "30px",
"background-color": "red",
});
});
js文件
$(document).ready(function () {
//设置样式,可以根据自己的意愿来设置
$("li").css("font-size",function(index,value){
//形参index 指的是当前元素的索引号
//形参value 指的是当前元素要设置的样的值。此处指font-size的值
console.log(index);
console.log(value);
});
});
输出结果:
js文件
$(document).ready(function () {
//设置样式,可以根据自己的意愿来设置
$("li").css("font-size",function(i,v){
//每一行设置不同的字体大小
return (i+1) * parseInt(v) + "px";
});
});
输出结果:
js文件
$(document).ready(function () {
//设置样式,可以根据自己的意愿来设置
$("li").css("font-size",function(i,v){
//只设置第三个
if(i === 2){
return (i+1) * parseInt(v) +"px";
}
});
});
输出结果:
![](https://i-blog.csdnimg.cn/blog_migrate/d2b3dd5136ecc691ebde28272dda60e2.png)