【问题标题】:JQuery Resize Not Working When Loading加载时JQuery调整大小不起作用
【发布时间】:2013-04-04 12:01:17
【问题描述】:

我有一个这样的 div:

<div class="first">
<img src="image/image1.gif" style="width:30%;display:inline-block"/> 
<img src="image/image2.gif" style="width:30%;display:inline-block"/> 
<img src="image/image3.gif" style="width:30%;display:inline-block"/>
<br />testing<br /><br />がらんどう
</div>

我希望它垂直居中并调整大小,所以我使用标准的 JQuery 代码:

$(window).resize(function(){

$('.first').css({
    position:'absolute',
    top: ($(window).height() - $('.first').outerHeight())/2
});
});

$(window).resize();

div 的 css 是这样的:

.first
{
position:absolute;
top:50%;
}

问题是: 加载时div不是垂直集中的,但是当你调整窗口大小时,它会集中..

你们能帮我弄清楚吗?谢谢!!

【问题讨论】:

  • 您的代码在$(document).ready() 处理程序中吗?
  • @DipeshParmar 是的,你的作品有效,因为你的小提琴设置为运行onLoad。就是这样。除了真正的代码需要一个事件,而不是一些小提琴设置
  • @Ian 是的,我想说的是 OP..但没有添加文字,因为所有答案都对我说......
  • 我认为我的命名有些混乱。我将 .first 更改为此并且它有效。谢谢大家:)

标签: jquery resize positioning center


【解决方案1】:

你的.resize() 电话在$(document).ready() 内,对吧?否则,没有或许多元素将无法准备好/可用。你可能想要:

$(document).ready(function () {
    $(window).resize(function(){
        $(".first").css({
            position:'absolute',
            top: function () {
                return ($(window).height() - $(this).outerHeight())/2;
            }
        });
    });
    $(window).resize();
});

另外,您想使用$(this).outerHeight() 而不是$('.first').outerHeight()

由于某些浏览器在调整大小时经常触发resize(有些只在调整大小结束时触发),缓存 jQuery window 对象可能“更好”:

$(document).ready(function () {
    var $window = $(window);
    $window.resize(function(){
        $('.first').css({
            position:'absolute',
            top: function () {
                return ($window.height() - $(this).outerHeight())/2;
            }
        });
    });
    $window.resize();
});

【讨论】:

  • 我的错误是我使用 $(document).resize( 而不是 $(window).resize( 但你的回答告诉我 =P +1
【解决方案2】:

您似乎想将您的'.first' div 放在窗口的中心。 如果就是这样,您实际上不需要调整大小事件。这将起作用

$(function () {
    var first = $('.first');
    first.css({
        'margin-top': -first.height();
    });
});

如果你想要它在窗口的中心。使用 CSS

.first {

position: fixed,
top: 50 %

}

如果您希望它位于文档中心或其他偏移父级,请提供position:absolute。 如果你愿意,你也可以为 left 做同样的事情。

即使您知道 '.first' div 的大小,您也可以直接在 css 上赋予 margin-top (=-height/2) 属性。比你不需要 javascript 代码。

如果您想使用顶部位置而不是将调整大小处理程序保留在 document.ready 处理程序中

$(function(){   
    var first = $('.first');
    $(window).resize(function(){ 
       first.css({
          top: ($(window).height() - first.outerHeight(true)) / 2
       });
    }).resize();  
})

【讨论】:

    猜你喜欢
    • 2011-02-05
    • 1970-01-01
    • 2014-05-12
    • 1970-01-01
    • 2014-11-14
    • 1970-01-01
    • 2011-12-14
    • 2015-10-22
    • 1970-01-01
    相关资源
    最近更新 更多