2012-03-14 51 views
0

我有这样的代码......jQuery的浏览器调整大小股利中心即使在滚动

<style type="text/css"> 
#container { 
    width: 200px; 
    height: 200px; 
    background-color: #567; 
} 
</style> 

<div id="container"> 
    My center div... 
</div> 


<script type="text/javascript"> 
$(window).resize(function(){ 
    $('#container').css({ 
    position:'absolute', 
    left: ($(window).width() - $('#container').outerWidth())/2, 
    top: ($(window).height() - $('#container').outerHeight())/2 
    }); 
}); 

// To initially run the function: 
$(window).resize(); 
</script> 

这个伟大的工程,除非我滚动到页面的底部,它不会在浏览器中的中间居中DIV屏幕基于我在页面位置的新坐标。所以我的问题是,如果我点击打开这个DIV,如果我滚动到长页面的底部,我能做些什么来集中DIV?

回答

1

您的脚本将只集中在页面顶部的窗口中。top是相对于文档而不是窗口 - 尝试位置:固定,然后您的居中脚本应该可以工作。

+0

这工作真棒!谢谢@whiteatom – Joe 2012-03-14 21:33:14

0

林不知道究竟你的问题,但我做类似这样的

var top= $(document).scrollTop()+($(window).height()/2) - ($('#container').outerWidth()/2); 
var left=(window.innerWidth/2) - ($('#container').outerWidth()/2); 
0

的水平中心的最佳方式是什么给margin: 0 auto CSS。至于垂直居中,你目前的方式已经足够好了。

1

也许是这样的:jsFiddle Demo Here

我增加和动画功能移动#container时滚动窗口:

var $scrollingDiv = $("#container"); 
$(window).scroll(function(){ 
    $scrollingDiv.stop().animate({"marginTop": ($(window).scrollTop() + 0) + "px"}, 500, 'easeInOutSine');    
}); 
+0

我喜欢这个。感谢斯科特 – Joe 2012-03-14 21:40:16

相关问题