我在手机上隐藏div方面得到了一些很好的帮助,但我还有一个额外的问题。我开始学到更多的JavaScript,绝对是个新手。
这是一个内容div的工作示例,该内容div隐藏在移动设备上,除非单击按钮。它的工作原理很好,只是最初打开div需要点击2次。我只想点击一下。
我已经在这类问题上看到了一些答案,并且已经尝试过了,但我现在无法理解它们。我不明白。
我如何重新工作我的脚本,使它只需点击一个按钮就可以打开div?谢谢!
function toggleGallery() {
var x = document.getElementById('image-gallery');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}#image-gallery {
display: block;
width: 600px;
border: 1px solid black;
}
#image-gallery li {
width: 150px;
height: 150px;
color: white;
text-align: center;
margin: 10px;
background-color: gray;
display: inline-block;
}
button {
display: none;
}
@media (max-width: 600px) {
#image-gallery {
display: none;
width: 100%;
}
button {
display: block;
}
}<div class="container">
<button onclick="toggleGallery()">Click to view images</button>
<p>I want to reveal this content on mobile with just one button click. </p>
<div id="image-gallery">
<ul>
<li>Image 1</li>
<li>Image 2</li>
<li>Image 3</li>
</ul>
</div>
</div>
<!--container-->
发布于 2017-08-14 18:44:07
在toggleGallery()函数中,将条件x.style.display === 'none'替换为x.style.display !== 'block'。
display属性最初并不等于none,这意味着您的函数将在该条件下将其设置为none,这意味着下次它将正常工作,并将其设置为block。通过检查display不等于block,它将在第一次工作。
发布于 2017-08-14 18:44:37
这是因为x.style只返回#image-gallery的内联样式。因为它一开始没有内联样式,所以x.style.display总是计算为未定义的。
实际上,您需要的是获取元素的计算显示属性(即您在开发人员工具中“计算样式”下看到的属性)。要做到这一点,只需使用window.getComputedStyle(element),即:window.getComputedStyle(x).display:
function toggleGallery() {
var x = document.getElementById('image-gallery');
var xDisplay = window.getComputedStyle(x).display;
if (xDisplay === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}#image-gallery {
display: block;
width: 600px;
border: 1px solid black;
}
#image-gallery li {
width: 150px;
height: 150px;
color: white;
text-align: center;
margin: 10px;
background-color: gray;
display: inline-block;
}
#image-gallery {
display: none;
width: 100%;
}
button {
display: block;
}<div class="container">
<button onclick="toggleGallery()">Click to view images</button>
<p>I want to reveal this content on mobile with just one button click. </p>
<div id="image-gallery">
<ul>
<li>Image 1</li>
<li>Image 2</li>
<li>Image 3</li>
</ul>
</div>
</div>
<!--container-->
发布于 2017-08-14 18:39:24
设置x.style.display = 'block'; at start style属性看不到css规则
https://stackoverflow.com/questions/45680880
复制相似问题