垂直对齐内容JavaScript

时间:2015-01-09 12:25:24

标签: javascript alignment vertical-alignment text-alignment text-align

HY,

基本上我想要实现的是垂直对齐某些内容,在我的情况下名称&工作

这里的问题是,在调整窗口大小时,我希望内容保持在中间位置。 我找到了一个小脚本,但我无法让它工作,仍然学习JS的基础知识。

我的标记如下:

  1. 导航
  2. 垂直内容
  3. 页脚(位置:绝对;底部:0;)//与底部对齐。
  4. 我创建了一个JSFiddle(http://jsfiddle.net/marianstroiu/khm52p0a/1/),所以你能看到我在说什么。

    function getWindowHeight() {
                var windowHeight = 0;
                if (typeof(window.innerHeight) == 'number') {
                    windowHeight = window.innerHeight;
                }
                else {
                    if (document.documentElement && document.documentElement.clientHeight) {
                        windowHeight = document.documentElement.clientHeight;
                    }
                    else {
                        if (document.body && document.body.clientHeight) {
                            windowHeight = document.body.clientHeight;
                        }
                    }
                }
                return windowHeight;
            }
            function setContent() {
                if (document.getElementById) {
                    var windowHeight = getWindowHeight();
                    if (windowHeight > 0) {
                        var contentElement = document.getElementById('v-content');
                        var contentHeight = contentElement.offsetHeight;
                        if (windowHeight - contentHeight > 0) {
                            contentElement.style.position = 'relative';
                            contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px';
                        }
                        else {
                            contentElement.style.position = 'static';
                        }
                    }
                }
            }
            window.onload = function() {
                setContent();
            }
            window.onresize = function() {
                setContent();
            }
    

    谢谢!

1 个答案:

答案 0 :(得分:1)

您正在使用bootstrap粘页脚模板将底部边距和页脚添加到body元素,因此您应该从窗口高度中减去2 * 60像素。修改后的jsfiddle

相关问题