javascript - jQuery的toggle函数是怎么实现的,不用jquery怎么用javascript写?

标签 javascript jquery css

您将如何编写一个切换开关,将元素的显示属性从 display:none 切换到 display:block;,或者无论如何,jquery 的切换可以操作的任何 css 属性 - 您将如何编写一个切换没有jquery的功能?

为什么不能在以下代码中将 javascript css 属性作为 bool 值?

<html>
<head>
<style type="text/css">
a {
 display:none;
}
</style>
<script type="text/javascript">

 function ab(a)
 {
   if(document.getElementById(a).style.display=='none')
   {
     document.getElementById(a).style.display="block";

  }
  else if(document.getElementById(a).style.display=="block")
   {
     document.getElementById(a).style.display="none";

    }
  }

 </script> 
 </head>
 <body>
 <div class="fg">
 <div style="width:100px;height:100px;border:2px solid blue;" onmouseover="ab('g');"
      onmouseout="ab('g');">
  <a id="g" href="http://www.dfadsafafa.com">lajflke</a></div></div>
 </body>
 </html>

最佳答案

你提到的解决方案看起来不错,但可以使它更简洁。

function toggle(id){
    var div1 = document.getElementById(id);
    if (div1.style.display == 'none') {
        div1.style.display = 'block'
    } else {
        div1.style.display = 'none'
    }
}

关于javascript - jQuery的toggle函数是怎么实现的,不用jquery怎么用javascript写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7943673/

相关文章:

javascript - .closest().next(.class) 未达到预期的 div

javascript - 理解 JavaScript originalEvent

css - <label/> 和 <a/> 之间不需要的换行符

html - scss 嵌套受制于语法和嵌套

java - JSTL:在自定义标签中使用 scriptlet

javascript - Heroku API 与curl 配合使用效果很好,但我在使用XMLHttpRequest 时遇到了麻烦。 XHR、Heroku 还是我的错?

javascript - 使用 Safari 隐藏视频文本轨道

javascript - 如何删除javascript中的最后一行?

javascript - 包含外部JS文件的内容

css - 在 Backbone Marionette 中使用 css 或区域管理 View