js鼠标点击“消失与出现”事件

  css:  #tops{
            position: relative;top: 200px;
            width: 200px;height: 100px;background: #4587f5;
        }
        #bottom{
            position: relative;top: 200px;
            width: 200px;height: 400px;background: #45f5db;
        }
html:
<div id="tops" onclick="a()"></div>
<div id="bottom"></div>

首先,我们需要建造两个盒子:

onclick=“a()”定义点击函数为a

 

 当我们点击蓝色盒子时,绿色消失

 

 再次点击,绿色出现

 

 

整体代码,如下:(js部分含有注释。)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #tops{
            position: relative;top: 200px;
            width: 200px;height: 100px;background: #4587f5;
        }
        #bottom{
            position: relative;top: 200px;
            width: 200px;height: 400px;background: #45f5db;
        }
    </style>
</head>
<body>
<div id="tops" onclick="a()"></div>
<div id="bottom"></div>
</body>
</html>
<script>
    const bottom=document.getElementById('bottom')
    let b=0;//定义变量b
    function a() {
     b++;//当点击蓝色盒子时,b自增
if (b%2==0){
    bottom.style.display='block'
    console.log('出现')//如果b的点击次数除2的余数为0,盒子出现
}else {
    bottom.style.display='none'
console.log('消失')//不为0时,消失。
}
    }
</script>

 

posted @ 2022-03-07 20:28  一克嗽  阅读(758)  评论(0)    收藏  举报