24-解决方案
6.6.2 解决方案
获取视区的尺寸;确定元素的宽度、高度和偏移量;利用一些算术运算将元素放在视区的中央:
jQuery(document).ready(function() {
jQuery('#bar').click(function() {
var viewportWidth = jQuery(window).width(),
viewportHeight = jQuery(window).height(),
$foo = jQuery('#foo'),
elWidth = $foo.width(),
elHeight = $foo.height(),
elOffset = $foo.offset();
jQuery(window)
.scrollTop(elOffset.top + (elHeight/2) - (viewportHeight/2))
.scrollLeft(elOffset.left + (elWidth/2) - (viewportWidth/2));
});
});
在最后一行中,将元素顶部偏移量加上元素高度的一半,确定元素的垂直中心。然后,减去视区高度的一半,确定窗口滚动的位置。最后,进行类似的计算,在水平方向上使视区居中。