如何在DIV中心放置水平滚动条

时间:2015-07-31 13:28:10

标签: jquery html css

我试图将水平滚动条放在该div的中心。我厌倦了window.scrollTo()但这适用于页面滚动而不适用于div滚动。

$(document).ready(function(){
    var outerContentWidth = $('.abc').width();
    var scrollPosition = outerContentWidth/2;
    $('.abc').scrollLeft(scrollPosition);

});

DEMO:fiddle

6 个答案:

答案 0 :(得分:7)

以下内容将为您提供所需的效果,并通过简单的jQuery更改滚动到div的中心:

$(document).ready(function(){
    var outerContent = $('.abc');
    var innerContent = $('.abc > div');

    outerContent.scrollLeft((innerContent.width() - outerContent.width()) / 2);        
});
  

此代码将滚动条设置为内部内容的中心。   但我们来看看为什么。我们知道scrollLeft的最小值是   零,最大值是inner.width() - outer.width()。所以,中途   很容易就是最大值的一半。

有关该主题的更多信息here

Demo

答案 1 :(得分:0)

$(document).ready(function(){
    var scrollPosition = ($('#viewContainer').width()/2 + $('.abc').width())/2;
    $('.abc').scrollLeft(scrollPosition);

});

答案 2 :(得分:0)

如果您想要滚动以便显示中间div,只需设置scrollPosition,如下所示:

var scrollPosition = $('.page').width()*2; // scroll by 2 pages, so third page is visible.

http://jsfiddle.net/cxkmkb0o/3/

否则,如果您希望中间页面也在视图中居中,则应该为我建议的内容添加偏移量。

编辑:你也应该注意到小提琴中的页面与“视图”的宽度不同。您应该将页面的width更改为min-width,以确保它们采用正确的宽度。另外,在定位元素时应考虑边界;每个边框增加了元素的宽度。 Here's the updated fiddle

答案 3 :(得分:0)

这是一个古老的问题,但是您现在可以使用scrollIntoView,具体取决于必须支持的浏览器:

$(document).ready(function(){ document.getElementById('center').scrollIntoView({ inline: 'center' }); });

Updated fiddle

答案 4 :(得分:0)

使用一些注释可能会有用,以便更好地理解我的方法:

function scrollMeTo($Parent, $Child) {

    let parentHalf = $Parent.width() / 2; // half of parent width
    let childHalf = $Child.width() / 2; //half of child width
    let childPos = $Child.position().left; // X pos of child (relative to screen)
    //We increase X with the center of the child (childHalf) - scrolling here we see the right half of the child;
    //We decrease X with the parentHalf to obtain perfect center;
    let scroll = childPos + childHalf - parentHalf; //how much we need to scroll to the element
    //We now add the needed scroll to the current scroll.
    let nextScroll = $Parent.scrollLeft() + scroll;
    $Parent.scrollLeft(nextScroll);
}

或用作一个线性:

function scrollMeTo($Parent,$Child){
       $Parent.scrollLeft($Parent.scrollLeft() + $Child.position().left + $Child.width() / 2 - $Parent.width() / 2);
}

答案 5 :(得分:0)

您可以通过Simplay实现此目的,

$(document).ready(()=>{
    $('#scroll').scrollIntoView({ inline: 'center' });
});

OR

$(document).ready(()=> {
    let outerContent = $('.abc');
    let innerContent = $('.abc > div');
    outerContent.scrollLeft((innerContent.width() - outerContent.width()) / 2);        
});