【问题标题】:How can i resolve same bug with jQuery scripts to center a DIV with percentage?如何使用 jQuery 脚本解决相同的错误,以百分比居中 DIV?
【发布时间】:2013-05-13 15:36:45
【问题描述】:

这是我的代码

<style>

.className{
width:55%;
height:auto;
margin:0 auto;
}

body{
text-align:center;
}

</style>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>

$(document).ready(function(){

$(window).resize(function(){

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

});
// To initially run the function:
$(window).resize();

});

</script>

当我打开我的页面时,我看到我的 DIV 没有居中,但是当我缩小并以完整模式重新打开浏览器的窗口时,DIV 完全居中,请帮助我,我快疯了 我尝试改变

这个

<script>

$(document).ready(function(){

$(window).resize(function(){

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

});
// To initially run the function:
$(window).resize();

});

</script>

有了这个(TXH TO Elhussein Hashem)

<script>
$(document).ready(function(){

     resizeFunction();

    window.onresize = function() {
        resizeFunction();
    };

     resizeFunction();

});

function resizeFunction(){
    $('.className').css({
        position:'absolute',
        left: ($(document).width() - $('.className').outerWidth())/2,
        top: ($(document).height() - $('.className').outerHeight())/2
    });
}
</script>

但结果并没有改变:(

我注意到,即使我刷新页面,当我缩小并重新打开浏览器窗口时,所有内容都会回到中心

这是DIV

<div class="className">
<div><img style="width:100%" src="http://i39.tinypic.com/5f506d.jpg"/></div>
</div>

P L Z 帮助 甲乙

【问题讨论】:

标签: jquery image html centering


【解决方案1】:

如果我们能看到页面会更容易,但您可以尝试使用 window.load。我猜,因为你的类有一个图像,所以在 .className 有一个宽度之前调用 ready (它知道它有一个图像,但不知道图像的大小)。

<script>
//window.load waits for graphics to finish loading before running
$(window).load(function(){
  $(window).resize(function(){
    $('.className').css({
      position:'absolute',
      left: ($(window).width() - $('.className').outerWidth())/2,
      top: ($(window).height() - $('.className').outerHeight())/2
    });
  });
  // To initially run the function:
  $(window).resize();
});
</script>

【讨论】:

  • 我也这么猜+1
  • @dave thx 1000,工作,但还有另一个小问题,现在当我打开网站几秒钟 1-2 时,我看到 div 像旧代码一样被窃听,但 1 2 秒后 div 是在页面中间自动居中,为什么?
猜你喜欢
  • 2016-03-02
  • 2011-07-14
  • 1970-01-01
  • 2013-11-29
  • 2012-12-23
  • 2013-08-04
  • 1970-01-01
  • 2013-09-18
  • 1970-01-01
相关资源
最近更新 更多