【问题标题】:how to constantly change display property with javascript如何使用javascript不断更改显示属性
【发布时间】:2018-05-07 11:41:03
【问题描述】:

脚本:

  let menu =  function(){
        var obj = document.getElementById("hidden")
        if(obj.style.display = "block"){
           obj.style.display = "none"
       //hide the div element with an ID #Hidden
        }else{
           obj.style.display = "block"
       //else show it 
        }
      }

        // I tried using buttons too, same result.

CSS

div#hidden{
       display:none;

    }

HTML:

<a href="javascript:menu()"id="info" > INFO </a> 

<div id="hidden">
     <!-- some stuff -->
</div>

我正在尝试“不断”更改带有 ID“隐藏”的 DIV 元素的显示属性以显示和隐藏 -VICEVERSA

my javascript code

显然这段代码可以运行,但是! 第二次调用此事件时,它不会运行或对我的代码执行任何操作。

if 语句中的代码被执行但没有做任何事情或改变我的显示属性

【问题讨论】:

标签: javascript css properties


【解决方案1】:

您的if 声明不正确。如下操作

obj.style.display === "block"

here你可以在javascript中找到更多关于比较运算符的信息

【讨论】:

    【解决方案2】:

    您应该在if 语句中使用比较运算符(=====),而不是赋值运算符(=

    【讨论】:

      【解决方案3】:

      见下面的代码:

      function func(){
      var obj=document.getElementById("hidden");
      if(obj.style.display==="block")
      obj.style.display="none"
      else
      obj.style.display="block"
      }
      <p id="hidden" style="display:none">I am the text<p>
      <button onclick="func()">click me</button>

      【讨论】:

      • 告诉更多帮助
      • 我不敢相信我怎么会错过这个,我已经在我的 if 语句中使用了 === 这个,但它从来没有成功过。
      • 老兄,你不知道我为了解决这个问题而更改了多少代码。谢谢人!
      • 我现在不能,我需要再等 3 分钟才能切换它 :'( -- 抱歉,我不好等一下
      • 完成 :) 它有一段时间让我检查一下,再次感谢
      猜你喜欢
      • 1970-01-01
      • 2011-04-04
      • 2013-02-20
      • 1970-01-01
      • 1970-01-01
      • 2019-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多