【发布时间】:2014-05-09 18:42:28
【问题描述】:
我有一个元素想要在页面中垂直居中。我想获取视口高度并从中减去页眉、页脚和主高度。结果数字将除以 3 并应用于元素的 margin-top。这工作正常,除非窗口垂直收缩时应用负数。
function getMargin() {
var wHeight = $(window).height();
var hHeight = $('header').height();
var mHeight = $('main').height();
var fHeight = $('footer').height();
var height_diff = (wHeight - hHeight - mHeight - fHeight) / 3 + "px";
//here is where its not working
if ($(height_diff) >= '30px') {
$('#content').css('margin-top', height_diff);
} else {
$('#content').css('margin-top', '40px');
};
console.log(height_diff);
}
$(window).resize(function(){
getMargin();
});
只要返回的数字(height_diff)大于 30px,就应用它作为边距,如果小于 30px 则使用默认值。我错过了什么?
【问题讨论】:
标签: javascript jquery