如何在DIV中心定位水平滚动条 [英] How to position horizontal scroll bar at center of DIV
问题描述
我试图在该div的中心放置水平滚动条。我厌倦了window.scrollTo(),但这适用于页面滚动而不适用于div滚动。
$(document).ready (function(){
var outerContentWidth = $('。abc')。width();
var scrollPosition = outerContentWidth / 2;
'('。abc')。scrollLeft(scrollPosition );
});
DEMO: fiddle 下面会给你想要的效果并通过jQuery中的简单更改滚动到div的中心:
$(document).ready(function() {
var outerContent = $('。abc');
var innerContent = $('。abc> div');
outerContent.scrollLeft((innerContent.width () - outerContent.width())/ 2);
});
此代码会将滚动条设置为内部内容的中心。
但让我们来看看为什么。我们知道scrollLeft的最小值是
零,最大值是inner.width() - outer.width()。因此,一半的
很容易就达到最大值的一半。
关于这个主题的更多信息在这里。
I was trying to position horizontal scroll bar at the center of that div. I tired with window.scrollTo() but this works for page scroll and not for div scroll.
$(document).ready(function(){
var outerContentWidth = $('.abc').width();
var scrollPosition = outerContentWidth/2;
$('.abc').scrollLeft(scrollPosition);
});
DEMO: fiddle
The following will give you your desired effect and scroll to the center of the div through a simple change in your jQuery:
$(document).ready(function(){
var outerContent = $('.abc');
var innerContent = $('.abc > div');
outerContent.scrollLeft((innerContent.width() - outerContent.width()) / 2);
});
This code will set the scroll bar to the center of the inner content. But lets examine why. We know the minimum value for scrollLeft is zero, and the maximum is inner.width() - outer.width(). So, half way is easily half the maximum.
There is plenty more information on the subject here.
这篇关于如何在DIV中心定位水平滚动条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!