简体   繁体   English

跨浏览器:如何根据视口高度调整元素的垂直位置?

[英]Cross Browser: How Can I Adjust the Vertical Position of an Element, Based on Viewport Height?

I've got a dock of icons that I would like vertically centered. 我有一堆想要垂直居中的图标。 This of course would vary, based on screen resolution, etc. What I've currently done, is got the height of a parent DIV, which is sized at 100% of the viewport: 当然,这取决于屏幕分辨率等。我目前所做的是获取父DIV的高度,该高度的大小为视口的100%:

    var pageHeight = $('#sidebar').height();

Then, I get the height of the icon container, as this is not predetermined in CSS: 然后,获得图标容器的高度,因为CSS中未预先确定:

    var socialDockHeight = (document.getElementById('social_dock_container').offsetHeight * numberOfIcons);

Note: this only retrieves the height of one icon, for some reason, perhaps because they are coded in an array? 注意:由于某种原因,这可能仅检索一个图标的高度,也许是因为它们是在一个数组中编码的? I then calculate the new position, and assign it to the element, via jQuery: 然后,我计算新位置,并通过jQuery将其分配给元素:

    var y = (pageHeight / 2) - (socialDockHeight / 2);
    $("#social_dock_container").css({ 
            top: y + "px"
    }).show();

This works great in Chrome, but not IE, FF, or Safari. 这在Chrome浏览器中效果很好,但在IE,FF或Safari中却无法使用。

You want to have your icons always beeing positioned in the middle of the screen? 您是否希望图标始终位于屏幕中间? If your Icons are not that big, why not do: 如果您的图标不够大,为什么不这样做:

#social_dock_container
{
    position: absolute;
    top: 50%;
}

EDIT 编辑

As Zee Tee mentioned, of course you need to set margin-top as followed: 正如Zee Tee所述,您当然需要按照以下步骤设置边距最高值:

$("#social_dock_container").css('margin-top', '-' + socialDockHeight / 2 + 'px' );

If you're not going to use $(window).height() , then use $('#sidebar').outerHeight(); 如果您不打算使用$(window).height() ,请使用$('#sidebar').outerHeight(); , so you get all the other good stuff like paddings and margins on the element. ,因此您可以获得元素上的所有其他好东西,例如填充和边距。

Also don't forget about when a user resizes their window. 另外,不要忘记用户何时调整窗口大小。 Use .resize(); 使用.resize(); for that. 为了那个原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM