jQuery 样式操作
1. 操作css方法
jQuery 可以使用css方法来修改简单元素样式,;也可以操作类,修改多个样式
//css以及html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="jquery-3.5.1.min.js"></script>
<style>
div{
width: 200px;
height: 200px;
background-color:black;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
(1) 参数只写属性名,则返回属性值 , 如:$(this).css(“color”)
<script>
$(function() {
console.log($("div").css("width"));
})
</script>
//控制台显示200px
(2) 参数是css(“属性名”,“属性值”),如果值是数字,可以不用跟单位和引号
<script>
$(function() {
$("div").css("width",300);
})
</script>
(3) 参数可以是对象的形式,方便设置多组数据,属性名和属性值用冒号隔开,属性可以不加引号
<script>
$(function() {
$("div").css({
width:400,
height:"400px",
backgroundColor: "red"
});
})
</script>
2.设置类样式方法
作用等同于以前的classList,可以操作类样式,注意操作类里面的参数不要加点
<style>
div{
width: 200px;
height: 200px;
background-color:black;
}
.current{
background-color: aqua;
}
</style>
(1) 添加类 $(“div”).addClass(“current”);
ps: 类名,所以不加点
//CSS
<style>
div{
width: 200px;
height: 200px;
background-color:black;
}
.current{
background-color: aqua;
}
</style>
//html 以及 js
<div></div>
<script>
$("div").click(function() {
$(this).addClass("current");
})
</script>
(2) 移除类 $(“div”).removeClass(“current”);
(3) 切换类 $(“div”).toggleClass(“current”);
ps:切换即有此类则移除,无此类则添加
3.类操作与className区别
原生JS中className 会覆盖元素原先里面的类名
jQuery 里面类操作只是对指定类进行操作,不影响原先的类名