【发布时间】:2015-03-07 18:33:48
【问题描述】:
喂,
基本上我想要实现的是垂直对齐一些内容,在我的例子中是名称和工作。
这里的问题是,在调整窗口大小时,我希望内容保持在中间。 我找到了一个小脚本,但我无法让它工作,还在学习 JS 的基础知识。
我的标记如下:
- 导航
- 垂直内容
- 页脚(位置:绝对;底部:0;)//与底部对齐。
我创建了一个 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();
}
谢谢!
【问题讨论】:
-
我试过了,但没有解决方案。我正在寻找一种 JS 方法。不过谢谢!
-
只是出于好奇:为什么您宁愿使用 JS 方法而不是 CSS 方法?因为只要有可用的 css 解决方案,它几乎总是比 js apporach 更可取,不是吗?
-
不,我刚才在比较,CSS 解决方案是最好的方法!再次感谢您!
标签: javascript alignment vertical-alignment text-alignment text-align