原生JS中隐藏元素的三种方法

<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
    <style>
        .box1{height:200px;width:200px;background:#f99;}
        .box2{height:200px;width:200px;background:#f99;display:block;}
        .box3{height:200px;width:200px;background:#f99;}
    </style>
</head>

<body>
    <div class="box1">1</div>
    <input type="button" class="btn1" value="点击1">
    <div class="box2">2</div>
    <input type="button" class="btn2" value="点击2">
    <div class="box3">3</div>
    <input type="button" class="btn3" value="点击3">
</body>
    <script>
//        1、hidden
        
        var box1 = document.querySelector(".box1");
        var btn1 = document.querySelector(".btn1");
        var type = 0;
        var type1 = 0;
        btn1.onclick = function(){
            if(type1 == 0){
                
                box1.hidden = true;
//                注意,设置hidden时不能给div加display:block属性
//                 (在部分老版本浏览器中可行)
                type1 = 1;
            }else{
                
                box1.hidden = false;
                
                type1 = 0;
            }
        }
        
//        2、display
        var box2 = document.querySelector(".box2");
        var btn2 = document.querySelector(".btn2");
        btn2.onclick = function(){
            if(type == 0){
                box2.style.display = "none";
                type = 1;
            }else{
                box2.style.display = "block";
                type = 0;
            }
        }
        
//        3、opacity
        var box3 = document.querySelector(".box3");
        var btn3 = document.querySelector(".btn3");
        btn3.onclick = function(){
            if(type == 0){
                box3.style.opacity = 0;
                type = 1;
            }else{
                box3.style.opacity = 1;
                type = 0;
            }
        }
    </script>
</html>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容