简体   繁体   English

垂直对齐内容JavaScript

[英]Align content vertically JavaScript

Hy, HY,

Basically what I want to achieve is to align some content vertically, in my case name & job. 基本上,我要实现的是在我的案例名称和工作中垂直对齐一些内容。

The issue here is, when resizing the window, I want the content to stay in the middle. 这里的问题是,在调整窗口大小时,我希望内容保留在中间。 I found a small script but I cannot get it to work, still learning the basics of JS. 我找到了一个小脚本,但仍然无法学习,仍然在学习JS的基础知识。

My markup is the following: 我的标记如下:

  1. Navigation 导航
  2. Vertically content 纵向内容
  3. Footer (position: absolute; bottom: 0;) // is aligned to bottom. 页脚(位置:绝对;底部:0;)//与底部对齐。

I created a JSFiddle ( http://jsfiddle.net/marianstroiu/khm52p0a/1/ ), so can you see what I'm talking about. 我创建了一个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();
        }

Thank you! 谢谢!

You are using bootstrap sticky-footer template that add bottom margin and footer to the body element so you should substract 2 * 60 pixel from window height. 您正在使用引导程序粘性页脚模板,该模板在主体元素上添加了底部边距和页脚,因此应从窗口高度中减去2 * 60像素。 Here is modified jsfiddle 这是修改的jsfiddle

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

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