让div在桌面上可见,在手机上切换可见性
我已经搜索了这个,但我的JavaScript知识非常基本,所以我可能错过了答案。让div在桌面上可见,在手机上切换可见性
我有一个图像库,我希望在桌面上默认可见。在移动设备上查看时,我希望该图库默认处于隐藏状态,但如果单击按钮仍然可见。
我已经创建了移动部分,使用我用于移动导航的一些代码。这部分工作正常......但很明显,因为我的按钮和图像库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';
}
}
你的代码是好的,只是在末尾添加脚本标记。 像我在为你做的小提琴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
谢谢!这很好。唯一的问题是我必须在移动设备上点击两次按钮才能打开它。只需点击一下,我就可以做到这一点吗?无论哪种方式,我都可以继续这个。 – sterlingcooper
更新:我把我的画廊包裹在另一个div中,包括一个“关闭窗口”按钮,然后添加一些js来关闭div并刷新页面,以便该人可以重新开始。 – sterlingcooper
太棒了!如果您将此答案标记为正确的答案将会很好 – TalGabay
它会被隐藏在小屏幕设备和屏幕比767px宽度可见。 CSS:
#image-gallery {
display: none;
}
@media (min-width:767px){
#image-gallery {
display: block;
}
}
然后切换功能buttion
function toggleDiv(id) {
var div = document.getElementById(id);
div.style.display = div.style.display == "none" ? "block" : "none";
}
感谢gudboisgn,我用TalGabay的方法解决了我的问题,但是您的代码也可能有助于我双击打开问题。唯一的问题是打开后无法再关闭它。 – sterlingcooper
您可以使用媒体查询结束puuting脚本标记一个很好的描述答案。 –