点击按钮显示/隐藏元素
让元素隐藏或显示, 最好是在css中设置一个类, 通过js控制类的变化来改变元素的状态.
<!DOCTYPE html>
<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">
<title>Document</title>
<style>
*{
padding: 0;
margin: 0;
}
div {
width: 200px;
height: 200px;
background-color: pink;
}
.hide {
display: none;
}
.show {
display: block;
}
</style>
</head>
<body>
<input type="button" value="点击隐藏" id="btn">
<div id="box"></div>
<script>
var btn = document.getElementById("btn");
var box = document.getElementById("box");
btn.onclick = function(){
//如果元素div当前是显示的, 就让他隐藏
if(btn.value == "点击隐藏"){
box.className = "hide";
btn.value = "点击显示";
}
else {
box.className = "show";
btn.value = "点击隐藏";
}
};
</script>
</body>
</html>