【发布时间】:2013-07-23 20:29:45
【问题描述】:
我正在使用以下脚本将主要内容 div 居中在查看区域的中心,这在页面加载或页面调整大小时似乎工作得很好,但是当页面刷新时,内容 div 会下降到左侧页面的一侧。
按刷新时可以在这里看到问题:
http://www.twin-focus-photography.co.uk/
<script>
$(document).ready(function(){
var positionContent = function () {
var width = $(window).width(); // the window width
var height = $(window).height(); // the window height
var containerwidth = $('.container').outerWidth(); // the container div width
var containerheight = $('.container').outerHeight(); // the container div height
$('.container').css({position:'absolute',
left: ($(window).width() - $('.container').outerWidth())/2,
top: ($(window).height() - $('.container').outerHeight())/2 });
};
//Call this when the window first loads
$(document).ready(positionContent);
//Call this whenever the window resizes.
$(window).bind('resize', positionContent);
});
</script>
编辑>>>>>>>>>>>>
好的,我现在已经根据一些建议进行了编辑,现在看起来像这样:
<script>
$(document).ready(function(){
var positionContent = function () {
var width = $(window).width(); // the window width
var height = $(window).height(); // the window height
var containerwidth = $('.container').outerWidth(); // the container div width
var containerheight = $('.container').outerHeight(); // the container div height
$('.container').css({position:'absolute',
left: ($(window).width() - $('.container').outerWidth())/2,
top: ($(window).height() - $('.container').outerHeight())/2 });
}
});
$(document).ready(function(){
//Call this when the window first loads
$(document).ready(positionContent);
//Call this whenever the window resizes.
$(window).bind('resize', positionContent);
});
</script>
这仍然不会在刷新时起作用,如果我调整页面大小......它在第一次加载时起作用......它起作用,点击 f5 并且它向左倾斜并停留在那里。
【问题讨论】:
-
试试
$(window).on('resize', positionContent).trigger('resize'); -
对我来说,在使用 Chrome 的 1600x900 上,即使在第一次加载时,网站也会偏离中心。请告诉我们您的浏览器和分辨率。
-
为什么要在
ready块内定义函数?您可以在块之外定义它并在单独的ready块中调用该函数。 -
top: ($(window).height() - $('.container').outerHeight())/2 });删除最后一个;? -
您定义的函数不在您绑定它的 domReady 调用的范围内。把它移到外面,它应该可以工作。此外:margin: 0 auto 和一些 display: table with vertical-align hacks 应该也可以解决问题。 ;)