【问题标题】:Jquery div not centering on page refreshJquery div不以页面刷新为中心
【发布时间】: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 应该也可以解决问题。 ;)

标签: jquery html


【解决方案1】:

效果很好。由于您在 document.ready 中编写了代码,因此它会在完全加载页面后将主要内容居中。如果您希望它在完全加载之前工作,您必须使用 CSS。

【讨论】:

  • 问题是该站点根本没有居中。他已经在使用 CSS。
  • 如果我点击刷新它什么也不做,只是坐在左边,但除此之外它工作正常。
【解决方案2】:

好的,我已经修好了,如果我改变第一个

$(document).ready(function(){

$(window).load(function(){

现在一切正常,即使在页面刷新时也是如此......这就是为什么我不知道......有人愿意评论吗?

【讨论】:

    猜你喜欢
    • 2011-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 2017-05-11
    相关资源
    最近更新 更多