1 实现消失隐藏

1-1 jquery实现(visible)

  1. <body>
  2. <div>hello world</div>
  3. <button id="btn">按钮</button>
  4. <script>
  5. $("#btn").click(function(){
  6. // 判断元素是否显示
  7. // is(":visiable")判断元素是否隐藏
  8. var isShow = $("div").is(":visible");
  9. console.log(isShow)
  10. if(isShow){
  11. $("div").hide(1000)
  12. }
  13. else{
  14. $("div").show(1000)
  15. }
  16. })
  17. </script>
  18. </body>

1-2 原生js实现

  1. <body>
  2. <div id="div" style="display: block;">hello world</div>
  3. <button id="btn">按钮</button>
  4. <script>
  5. var div = document.getElementById("div");
  6. var btn = document.getElementById("btn");
  7. btn.onclick = function(){
  8. if(div.style.display == "block"){
  9. div.style.display = "none";
  10. }else{
  11. div.style.display = "block";
  12. }
  13. }
  14. </script>
  15. </body>

1-3 jquery实现(toggle)

<body>
    <div id="div">hello world</div>
    <button id="btn">按钮</button>
    <script>
        $("#btn").click(function(){
            // toggle 融合hide和show方法
            $("div").toggle(1000);
        })
    </script>
</body>