平滑滚动到中心开始?

3

我正在使用一个滚动jquery插件,滚动的宽度是浏览器的宽度,所以当我的内容宽度小于浏览器宽度时,我希望内容从浏览器中心开始。

这里是我用来居中内容所需像素数量的代码。

JQUERY

var totalWidth = 0;
$('.scrollableArea img').each(function(){
     totalWidth += parseInt($(this).width(), 10);
}); 

//totalWidth is the width of the content

var containWidth = $('#makeMeScrollable').width(); //browser width

containWidth /= 2;
totalWidth /= 2;
startWidth = containWidth - totalWidth;

有没有办法让滚动内容从左侧开始 startWidth 距离处开始?

如果内容宽度小于浏览器宽度,剩余的滚动区域会填充 75px 的 div。

因此,HTML 如下:

HTML

<div class="scrollableArea">
   <img/>
   <img/>
   <img/>
   <div class="filler"/>
   <div class="filler"/>
   <div class="filler"/>
   <div class="filler"/>
   ...etc
</div>

以下是插件网站http://www.smoothdivscroll.com/

2个回答

0

Smooth Div Scroll有一个名为move的方法,您可以使用它来使滚动条移动指定数量的像素。

因此,如果您想将其向右滚动100个像素,则可以像这样使用该方法:

$("#makeMeScrollable").smoothDivScroll("move", 100);

因此,如果您知道以像素为单位的起始位置,您可以在滚动条初始化时进行移动。我尚未测试过此代码,但应该可以使用类似以下内容的东西:

$("#makeMeScrollable").smoothDivScroll({
    setupComplete: function(eventObj, data) {
        $("#makeMeScrollable").smoothDivScroll("move", startWidth);
    }
});

希望我正确理解了你的问题。:-)


0

jQuery v1.8.3+ 包含内置的浏览器滚动效果。您可以按照以下方式利用这个内置功能:

$('.scrollableArea').scrollLeft(startWidth );

这里提供了jQuery源代码:

// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );

jQuery.fn[ method ] = function( val ) {
    return jQuery.access( this, function( elem, method, val ) {
        var win = getWindow( elem );

        if ( val === undefined ) {
            return win ? (prop in win) ? win[ prop ] :
                win.document.documentElement[ method ] :
                elem[ method ];
        }

        if ( win ) {
            win.scrollTo(
                !top ? val : jQuery( win ).scrollLeft(),
                 top ? val : jQuery( win ).scrollTop()
            );

        } else {
            elem[ method ] = val;
        }
    }, method, val, arguments.length, null );
};
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接