在移动设备上当前视口的中心显示div [英] show div in the center of current viewport on mobile devices

查看:253
本文介绍了在移动设备上当前视口的中心显示div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在当前视口的中心显示div?我特别要求移动设备,因为他们是最有问题的。

How do you show a div in the center of the current viewport? I am asking specifically for mobile devices, because they are the most problematic.

例如,我有2个按钮,显示相同的div。一个在页面的顶部,一个在底部。页面的高度为2个视口高度。如果所呈现的div的padding-top为40px,那么当按下底部按钮时div将不可见。显然,该解决方案对于移动设备不够灵活。
你推荐什么解决方案?

For example, I have 2 buttons that show the same div. One at top of the page, and one at the bottom. The page's height is 2 viewport heights in total. If the padding-top of the presented div is 40px, then the div will not be visible when the bottom button is being pressed. Clearly this solution isn't flexible enough for mobile devices. What solution do you recommend?

DIAGRAM:如果我将padding-top设置为40px,绿色div将出现在页面的顶部如果按下底部的红色按钮,绿色div也会出现在顶部,40px。它甚至不可见的用户。它应该出现在从第二个视口(用户看到的屏幕)顶部40像素。我希望有助于。

DIAGRAM: If i set the padding-top to 40px, the green div will appear at the top of the page (as shown) If the bottom red button is pressed, the green div will also appear at the top, 40px from it. It isn't even visible to the user. It should appear 40px from the top of the second viewport (the screen that users sees.) I hope that helps.

推荐答案

使用 position:fixed

function toggleDiv() {
    var div = document.getElementById('togglable');
    if (div.style.display !== 'none') {
        div.style.display = 'none';
    }
    else {
        div.style.display = 'block';
    }
};

#container-parent {
  position: absolute;
  background-color: #eee;
  height: 95%;
  width: 90%;
  overflow: scroll;
}
#container {
  height: 500px;
}
#togglable {
  position: fixed;
  top: 10%;
  height: 80%;
  left: 25%;
  width: 50%;
  background-color: red;
}
#spacer {
  height: 90%;
  
}

<div id="container-parent">
  <div id="container">
    <input type=button onclick="toggleDiv()">
    <div id="togglable"></div>
    
    <div id="spacer">
      <!-- I don't know how you have got your buttons attached but the point is that `position: fixed` positions the togglable div relative to the viewport -->
    </div>
    <input type=button onclick="toggleDiv()">
  </div>
</div>

这篇关于在移动设备上当前视口的中心显示div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆