、私は両方の矢印ハンドラを "合併"。
次に、スクロールされる幅に基づいて「スクロール」速度を決定するために必要な計算がありますが、必ずしも要素の幅の100%である必要はありません。
このスクリプトでは、100%スクロールの速度を簡単に決定できます。
次に、すでに距離がスクロールされている場合に速度を計算します。
CodePen
$(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
--first 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 px ...この[CodePen v2](https://codepen.io/Bes7weB/pen/yXbaYY?editors=0010) –
のように、スライダの幅に設定できます。今度は、スクロールするたびにスピードがリセットされます。スライダの残りの幅が短くなると、速度が調整されます。20pxをループする前に、この動作を再現する方法はありますか? – Scott