Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

jquery - How to position horizontal scroll bar at center of DIV

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...