×46 2022-09-20 16:46 采纳率: 100%
浏览 38
已结题

两个div怎么实现点击一次一个出现,另一个消失

两个div位置一样,样式一样,z-index不一样,怎么实现点击一次使div高的消失,div低的出现,再点击一次,div高的出现,div低的消失

  • 写回答

4条回答 默认 最新

  • 关注

    用js 设置他们的 display属性,或者用js 降低zindex,使其比另一个小。我给你个参考代码

    <!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>
            .box1 {
                width: 500px;
                height: 500px;
                background-color: #ccc;
                position: absolute;
                z-index: 1;
            }
            .box2 {
                width: 500px;
                height: 500px;
                background-color: red;
                position: absolute;
                z-index: 0
            }
            .box3 {
                width: 500px;
                height: 500px;
                background-color: #ccc;
                position: absolute;
                z-index: 1;
                left: 500px
            }
            .box4 {
                width: 500px;
                height: 500px;
                background-color: red;
                position: absolute;
                z-index: 0;
                left: 500px
            }
        </style>
    </head>
    <body>
        <!-- 方法一 -->
        <div class="box1" onclick="clickBox()">1</div>
        <div class="box2" onclick="clickBox2()">2</div>
        <!-- 方法二 -->
        <div class="box3" onclick="hideBox()">1</div>
        <div class="box4"onclick="hideBox()">2</div>
        <script>
            //如代码,默认情况下  ziindex 大的显示在最上层
            let box1 = document.getElementsByClassName('box1')[0];
            let box2 = document.getElementsByClassName('box2')[0];
            function clickBox() {
                box1.style.zIndex = 0;
                console.log(box1.style)
            }
            function clickBox2() {
                box1.style.zIndex = 1;
            }
    
            // 或者用这个方法, 
    
            let box3 = document.getElementsByClassName('box3')[0];
            let box4 = document.getElementsByClassName('box4')[0];
            function hideBox() {
                if (box3.style.display == 'block' || box3.style.display == '') {
                    box3.style.display = 'none';
                } else {
                    box3.style.display = 'block';
                }
            }
        
        </script>
    </body>
    </html>
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 9月28日
  • 已采纳回答 9月20日
  • 创建了问题 9月20日

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分