gpt4 book ai didi

javascript - 平滑滚动从中心开始?

转载 作者:行者123 更新时间:2023-12-01 01:47:44 24 4
gpt4 key购买 nike

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

最佳答案

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

关于javascript - 平滑滚动从中心开始?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18305246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com