切换 - 隐藏和显示

Toggle - Hide and show

我复制了 w3schools 的隐藏和显示切换,但我希望将其反转,这样额外的信息从一开始就不存在,但按钮会显示它。

这是代码:

html:

<button onclick="myFunction()">Click Me</button>

<div id="myDIV">
     This is my DIV element.
</div>

js:

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

如有任何帮助,我们将不胜感激!

解决方法很简单:隐藏 div.

<div id="myDIV" style="display:none"> 
    This is my DIV element. 
</div>

如果你把它隐藏在 css 中会更酷:

<div id="myDIV"> 
    This is my DIV element.
</div>

还有你的 css:

#myDIV {
    display: none;
}

您只需在代码中添加 display : none。

function myFunction() {
var x = document.getElementById('myDIV');
if (x.style.display === 'none') {
    x.style.display = 'block';
} else {
    x.style.display = 'none';
   }
}
<button onclick="myFunction()">Click Me</button>

<div id="myDIV" style="display:none;">
     This is my DIV element.
</div>

这是一个片段示例

设置样式以从头隐藏元素 (display:none)。点击切换。

document.getElementById('myButton').onclick = function() {
  var x = document.getElementById('myDIV');
  x.style.display = x.style.display === 'none' ? 'block' : 'none';
};
<button id='myButton' >Click Me</button>

<div id="myDIV" style="display:none">
     This is my DIV element.
</div>

我为我们提供了一个实用程序 CSS class 为此:

.is--hidden {
    display: none;
} 

然后就可以默认应用到元素上了:

<button class="mybutton">Click Me</button>
<div class="example is--hidden">Some Text</div>

并通过jQuery切换它:

$('.mybutton').on('click', function () {
    $('.example').toggleClass('is--hidden');
})

Fiddle: https://jsfiddle.net/tL5mj54n/

无需更改样式或 HTML。您的 javascript 应如下所示:

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

function myFunction() {
var x = document.getElementById('myDIV');
if (x.style.display != 'none') {
    x.style.display = 'none';
} else {
    x.style.display = 'block';
   }
};

第一个函数运行并隐藏您的 div,第二个函数对点击做出反应并切换 div。