2013-08-19 30 views
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从左边走呢?

如果内容宽度小于浏览器宽度,则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/

回答

0

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); 
}; 
}); 
0

平滑滚动股利有a method called move,使用它可以使滚动移动您指定的像素数。

所以,如果你想让它滚动100个像素给你使用这样的方法正确:

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

所以如果你有在你想让它开始像素位置,可以使移动当滚动器已经初始化时。我没有测试过这个代码,但它应该沿着这些线路工作:

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

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