所以在这里,我 “合并” 两个箭头处理程序。
然后,根据要滚动的宽度确定“滚动”速度需要进行计算,该滚动宽度可能不总是元素宽度的100%。
该脚本允许您轻松确定100%滚动的速度。
然后,它计算速度,如果已经有一个距离滚动。
$(document).ready(function(){
function moveit(arrow){
// Adjust you delay here
var delay = 2000; // delay to scroll 100%
var animationDelay;
var slider = arrow.siblings(".g_scroll");
var distance = slider.width();
var scrolled = slider.scrollLeft()+1; // +1 is to avoid infinity in the math below
if(arrow.hasClass("scroller_l")){
distance = -distance;
animationDelay = -distance * (-distance/delay)*(-distance+scrolled);
}else{
animationDelay = distance * (distance/delay)*(distance-scrolled);
}
slider.stop().animate({scrollLeft:distance}, animationDelay, 'linear');
}
function stop(arrow){
arrow.siblings(".g_scroll").stop();
}
$('.scroller_l, .scroller_r').hover(function(){
moveit($(this));
},function() {
stop($(this));
});
}); // ready
CodePen
- 第一个answer--
首先,你不能使用相同的id
不止一次。
所以我从你的HTML中删除了id="left"
和id="right"
。
现在的诀窍是通过使用$(this)
将箭头悬停到您的功能。
并找到.g_scroll
元素是它的兄弟姐妹。
$(document).ready(function(){
function loopRight(arrow){
arrow.siblings(".g_scroll").stop().animate({scrollLeft:'+=20'}, 'fast', 'linear', loopRight);
}
function loopLeft(arrow){
arrow.siblings(".g_scroll").stop().animate({scrollLeft:'-=20'}, 'fast', 'linear', loopLeft);
}
function stop(arrow){
arrow.siblings(".g_scroll").stop();
}
$('.scroller_r').hover(function(){
loopRight($(this));
},function() {
stop($(this));
});
$('.scroller_l').hover(function(){
loopLeft($(this));
},function() {
stop($(this));
});
});
CodePen
这看起来不错!现在唯一的问题是悬停被过早地触发 - 任何想法? – Scott
它滚动+或 - 20像素...您可以将其设置为滑块宽度,如[CodePen v2](https://codepen.io/Bes7weB/pen/yXbaYY?editors=0010) –
几乎完美!现在每次滚动一定数量时,速度都会重置。即当剩余的滑块宽度缩短时,调整速度。在循环20px之前 - 是否有办法复制这种行为? – Scott