【问题标题】:vertically align child div with jquery jumps on browser resize垂直对齐子 div 与 jquery 在浏览器调整大小时跳转
【发布时间】:2014-01-23 16:42:31
【问题描述】:

我正在学习这里的技术:

Vertically centering child div in parent container with JavaScript on page load is not setting position?

当我不知道容器的高度时,这允许我垂直居中一个 div。

一切正常,但是在 Safari 7.0.1 和 Chrome 32.0.1700.77 中,垂直对齐的 div 在浏览器调整大小时向上移动了大约 30 像素。在 Firefox 中,它只显示 Safari 和 Chrome 在浏览器调整大小时将 div 移动到的位置(无跳转)。

加载时,在浏览器调整大小之前:

<div id="s1" class="wrp_item" style="bottom: 257.1px;">

浏览器调整大小后:

<div id="s1" class="wrp_item" style="bottom: 286.2px;">

您可以在此处查看我正在使用的代码/标记示例,尽管我无法在 JS Fiddle 上复制该问题:

http://jsfiddle.net/RKhmY/

重现 Safari/Chrome 中的错误的在线演示。请注意在 Firefox 中该错误如何不显示: http://so.s2371.gridserver.com/test.html

任何想法在浏览器调整大小时额外像素来自哪里,从而导致跳跃?

【问题讨论】:

    标签: javascript jquery css


    【解决方案1】:

    您已经在 dom 就绪处理程序中绑定了窗口调整大小处理程序,因此无需使用此语法

    $(function () { //This line should be removed
        $(window).resize(function () {
            homepageLead();
        }).resize();
    }); //This line should be removed
    

    只需删除 $(function () { 和 });

    http://jsfiddle.net/RKhmY/2/

    【讨论】:

    • 这并没有阻止浏览器调整大小的跳转。几乎就像页面加载没有正确定位一样。在浏览器调整大小时,它会显示正确的位置。
    【解决方案2】:

    如果换一种方式可能会有所帮助:

    • 将内容 (#s1) 从顶部与 css 对齐 50%。
    • 获取内容的高度 (#s1)。
    • 给内容 (#s1) 内容高度的负边距 / 2。

    jsFiddle

    CSS:

    div.relative { position: relative; }
    section#hero div.item, section#hero { min-height: 750px; position: relative;}
    section#hero .wrp_item { width: 100%; position: absolute; top: 50%;}
    section#hero .wrp_item .wrp_item_inner { padding: 0px 20px; }
    

    jQuery:

    jQuery(document).ready(function($) {
    
                var homepageLead = function () {
                    var message = $('#s1'),
                        message_height = message.height();
                    return message.css('margin-top', -message_height / 2);
                };
    
                $(function () {
                    $(window).resize(function () {
                        homepageLead();
                    }).resize();
                });
    
        // end     
        });
    

    【讨论】:

    • 不错的方法,感谢您清理 JS。不幸的是,在加载和浏览器调整大小之间仍然存在跳转。这种跳跃只发生在 Safari 和 Chrome 上。
    • 我尝试使用 margin-top、paddingTop、top、bottom。不管我将 div 放在哪里,我仍然会在浏览器调整大小时得到这个跳跃。
    • 试试 message.outerHeight();而不是 message.height();在 jQuery 中。如果这解决了问题,那是因为 .height() 不计算 div 的填充。
    • 我试过高度、outerHeight 和 innerHeight。都产生相同的结果。
    • 你能在网上做个测试让我看看问题吗?
    【解决方案3】:

    我开始认为这可能是我的 CSS 的错误。我已经尝试过其他具有相同错误的插件。

    作为参考,如果有人有同样的问题,下面的链接对我有用,没有任何跳转:

    https://github.com/BrandonJacoby/Midway.js

    【讨论】:

      猜你喜欢
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-28
      • 2012-02-15
      • 1970-01-01
      • 1970-01-01
      • 2016-11-27
      • 2017-11-05
      相关资源
      最近更新 更多