在桌面上显示div,在移动设备

时间:2017-08-07 20:16:40

标签: javascript html css

我已经搜索了这个,但我的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';
}
}

2 个答案:

答案 0 :(得分:0)

它将隐藏在小屏幕设备中,并且在大于767px宽度的屏幕中可见。 css:

#image-gallery {
display: none;
}

@media (min-width:767px){
   #image-gallery {
     display: block;
    }
}

然后是按钮的切换功能

function toggleDiv(id) {
    var div = document.getElementById(id);
    div.style.display = div.style.display == "none" ? "block" : "none";
}

答案 1 :(得分:0)

您的代码没问题,只需在最后添加脚本标记即可。 就像我为你做的小提琴一样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末尾的明确答案