一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第11天,点击查看活动详情。
jquery样式操作
操作css方法
jquery可以使用css方法来修改简单元素的样式,也可以操作类,修改多个样式。
1.参数只写属性名,则是返回属性值
$(this).css("color");
2.参数是属性名,属性值,逗号分隔,是设置一组样式,属性必须加引号,值如果是数字可以不跟单位和引号
$(this).css("color","red");
3.参数可是是对象形式,方便设置多组样式。属性名和属性值用冒号隔开,属性可以不加引号。
$(this).css({"color":"white","font-size":"20px"});
接下来代码展示一下
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="../jquery-3.6.0.js"></script>
<title>Document</title>
<style>
div {
width: 200px;
height: 200px;
background-color: pink;
}
</style>
</head>
<body>
<div></div>
<script>
$(function(){
//返回属性值
console.log($("div").css("width"));
//设置一组样式
// $("div").css("width","300px")
//设置多组样式
$("div").css({
width:400,
height:400,
backgroundColor:"red",
})
})
</script>
</body>
</html>
注意:如果是复合属性则必须次采取驼峰命名法,如果值不是数字,则需要加引号
操作类
设置类样式方法
作用等同于以前的classList,可以操作类样式,注意操作类里面的参数不要加点。
1.添加类
$("div").addClass("current");
2.移除类
$("div").removeClass("current");
3.切换类
$("div").toggleClass("current");
类操作与ClassName区别
原生js中的ClasName会覆盖元素原先里面的类名。
jquery里面类操作只是对指定类进行操作,不影响原先的类名
在这里举个例子,假设有一个宽150px,高150px,其背景颜色为粉色的盒子,我们要设置一个类作为附加类来证明对指定类进行操作,不影响原来的类名,这个附加类的背景色为红色,且在鼠标点击时要呈现360旋转的效果,以下是代码示例:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="../jquery-3.6.0.js"></script>
<title>Document</title>
<style>
div{
width: 150px;
height: 150px;
background-color: pink;
margin: auto;
transition: all 1s;
}
.two {
background-color: red;
transform: rotate(360deg);
}
</style>
</head>
<body>
<div class="one"></div>
<script>
$(function(){
$("div").click(function(){
$(".one").addClass("two");
})
})
</script>
</body>
</html>