我搜索过这个,但我的 javascript 知识非常基础,所以我可能错过了答案。
我有一个图片库,我希望它在桌面上默认可见。在移动设备上查看时,我希望该图库默认隐藏,但在单击按钮时仍然可见。
我已经创建了移动部分,使用了一些用于移动导航的代码。那部分工作正常......但显然因为我的按钮和图像库 div 默认设置为“不显示”,所以它不会显示在桌面上。但是我不知道如何使用相同的内容来实现这两种情况。
我怎样才能让它在桌面上可见,并在移动设备上实现可选切换?谢谢!
HTML:
<div class="container">
<button onclick="toggleGallery()">Click to view images</button>
<p>I want the hidden image-gallery div to show up here despite being display none.</p>
<div id="image-gallery" style="display:none;">
<ul>
<li>Image 1</li>
<li>Image 2</li>
<li>Image 3</li>
</ul>
</div>
</div><!--container-->
CSS:
#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: block;
width: 100%;
}
button {
display: block;
}
#image-gallery li {
border: 1px solid red;
}
}
JS:
function toggleGallery() {
var x = document.getElementById('image-gallery');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
最佳答案
您的代码没问题,只需在末尾添加脚本标签即可。 就像我为你制作的 fiddle 一样here
toggleGallery() 未被删除。
<div class="container">
<button onclick="toggleGallery()">Click to view images</button>
<p>I want the hidden image-gallery div to show up here despite being display none.</p>
<div id="image-gallery">
<ul>
<li>Image 1</li>
<li>Image 2</li>
<li>Image 3</li>
</ul>
</div>
</div>
<!--container-->
<script>
function toggleGallery() {
var x = document.getElementById('image-gallery');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
</script>
Here关于将脚本标记放在 HTML 的末尾,您有一个详细描述的答案
关于javascript - 使 div 在桌面上可见,在移动设备上切换可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45555037/