【问题标题】:Smooth Scroll to start in center?平滑滚动以从中心开始?
【发布时间】:2013-08-19 01:17:50
【问题描述】:

我正在使用滚动 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

如果内容宽度小于浏览器宽度,则 scrollDiv 的其余部分将填充 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/

【问题讨论】:

    标签: javascript jquery smooth-scrolling


    【解决方案1】:

    jQueryv1.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 );
    };
    });
    

    【讨论】:

      【解决方案2】:

      Smooth Div Scroll 具有a method called move,您可以使用它使滚动条移动您指定的像素数。

      因此,如果您希望它向右滚动 100 像素,请使用如下方法:

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

      因此,如果您有希望它开始的像素位置,则可以在滚动条初始化时进行移动。我还没有测试过这段代码,但它应该可以与以下内容一起使用:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-11-19
        • 2018-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多