如何将DIV设置为style.display ="none";默认? [英] How do I make a DIV set to style.display = "none" by default?

查看:67
本文介绍了如何将DIV设置为style.display ="none";默认?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个按钮,当其被点击时将显示其他文本,但是,我只能将其设置为

I'm trying to make a button that will display additional text when it's hit, however, I can only make it either

  • a)默认显示文本或
  • b)默认情况下隐藏文本,但是该按钮不起作用.

这是按钮的JS代码:

function showInfo() {
  var x = document.getElementById("myDIV");
  
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div id="myDIV">
 Hello World
</div>
<button type="button" class="btn btn-primary" click="showInfo()">
Show Info
</button>

有没有一种方法可以将默认的style.display设置为none?

Is there a way I can set the default style.display to none?

推荐答案

您的处理程序是 click .它必须是 onclick .另外,我建议您将 display:none 的类添加到您的 div 中,或像这样简单地内联它:

Your handler is click. It needs to be onclick. Also, I recommend either adding a class with display:none to your div, or simply inlining it, like this:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div id="myDIV" style="display: none">
 Hello World
</div>
<button onclick="showInfo()">
Show Info
</button>

然后您的JS如下所示:

Then your JS can look like this:

function showInfo() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    return x.style.display = "block";
  }
  return x.style.display = "none";
}

演示

function showInfo() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    return x.style.display = "block";
  }
  return x.style.display = "none";
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
    <div id="myDIV" style="display: none">
     Hello World
    </div>
    <button onclick="showInfo()">
    Show Info
    </button>

这篇关于如何将DIV设置为style.display ="none";默认?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆