×

学习Javascript中隐藏元素的几种方法:hidden、diplay和opacity

作者:andy0012020.09.16来源:Web前端之家浏览:133评论:0
关键词:js

学习Javascript中隐藏元素的几种方法:hidden、diplay和opacity。

<html>
<head>
<meta charset="utf-8">
<title>学习Javascript中隐藏元素的几种方法 - Web前端之家https://jiangweishan.com/</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>


温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/js20200916a2.html

网友评论文明上网理性发言 已有0人参与

发表评论:

最新留言

首页|JavaScript|HTML|HTML4|HTML5|CSS3|开发工具|性能优化|移动开发|前端教程|性能优化|开发工具|酷站欣赏|UI设计|前端教程

Copyright © 2020 Web前端之家(www.jiangweishan.com) 版权所有 All Rights Reserved.
粤ICP备12067512号-1

Copyright Your WebSite.Some Rights Reserved.

Powered By Z-BlogPHP 1.6.5 Valyria