美文网首页
原生JS中隐藏元素的三种方法

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

作者: NisemonoC | 来源:发表于2019-12-02 09:29 被阅读0次
<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>

相关文章

网友评论

      本文标题:原生JS中隐藏元素的三种方法

      本文链接:https://www.haomeiwen.com/subject/dirxgctx.html