使用className方式更改页面样式
<!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>
.son {
width: 30vmin;
height: 30vmin;
color: white;
background-color: blue;
}
.father {
width: 40vmin;
height: 40vmin;
margin-top: 10vmin;
background-color: red;
color: blue;
}
</style>
</head>
<body>
<div class="son">文本</div>
<img src="" alt="">
<script>
var text = document.querySelector('div')
var flag = 0
text.onclick = function () {
if (flag == 0) {
//让我们当前元素的类名改为了father
/* this.className = 'father' */
//要使原先类名存在,就写为
this.className='son father'
flag = 1
} else {
this.className = 'son'
flag = 0
}
}
</script>
</body>
</html>
这是一个HTML代码片段。它创建了一个网页,其中包含一个带有初始类名为 “son” 的 <div>
元素。当点击该 <div>
元素时,通过JavaScript代码,它会在 “son” 和 “father” 两个类名之间切换,以改变元素的外观。
具体而言,当点击 <div>
元素时,会触发 onclick
事件处理程序。如果 flag
变量的值为0,则将 <div>
元素的类名更改为 “son father”,即同时具有 “son” 和 “father” 两个类名。如果 flag
变量的值为1,则将 <div>
元素的类名更改为 “son”。这样就实现了类名的切换,从而改变了元素的样式。
此代码利用CSS样式表中定义的样式规则来设置元素的宽度、高度、背景颜色和文本颜色。
效果图
点击前
注意此时类名为son
点击后
注意此时类名为son father