如果要修改的样式比较多,直接通过操作style属性会比较繁琐,此时可以通过操作className属性的方式来修改。
语法形式:
元素.className = '类名'
直接使用className 会覆盖以前的类名。所以,如果要保留以前的类名,需要把以前的类名也增加上,例如,以前的类名是nav,现在想增加box类名,那么应该使用:
元素.className = 'nav box'
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 200px;
height: 200px;
background-color: pink;
}
.box {
width: 300px;
height: 300px;
background-color: blue;
margin: 100px auto;
padding: 10px;
border: 1px solid #000;
}
</style>
</head>
<body>
<div></div>
<script>
// 1. 获取元素
const div = document.querySelector('div')
// 添加类名
// 此处后面类名前面不用加点(.)
div.className = 'box'
</script>
</body>
</html>