重新排列 js 以适应更大的灵活性

Rearranging js to accommodate more flexibility

如何让这个 js 只影响原始悬停元素的子元素,而不给所有单独的 .g_scroll 或 .left/.right 标签 ID?

function loopRight(){
      $('.g_scroll').stop().animate({scrollLeft:'+=20'}, 'fast', 'linear', loopRight);
  }

  function loopLeft(){
      $('.g_scroll').stop().animate({scrollLeft:'-=20'}, 'fast', 'linear', loopLeft);
  }

  function stop(){
      $('.g_scroll').stop();
  }


  $('#right').hover(function () {
     loopRight().children();
  },function () {
     stop();
  });

  $('#left').hover(function () {
     loopLeft();
  },function () {
     stop();
  });

JSfiddle(令人困惑,但有必要)html 结构:https://jsfiddle.net/6rbn18cL/

演示如何重命名它:https://jsfiddle.net/z9u3azqy/

所以在这里,我 "merged" 两个箭头处理程序。
然后,需要根据要滚动的宽度计算 "scroll" 速度,它可能并不总是元素宽度的 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




--第一个回答--

首先,您不能多次使用同一个 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

您可以传递事件对象并从那里找到合适的容器。

$('.scroller_l').hover(loopRight, stop);
$('.scroller_r').hover(loopLeft, stop);

如果您像上面那样将函数作为参数传递,这将自动完成。

要为每个实例动态查找滚动容器,您可以使用 类 查找相对于当前目标的容器:

var el = $(ev.currentTarget),
    parent = el.closest('.country_holder'),
    container = parent.find('.g_scroll');

查看工作示例 here

此时你可以问问自己loopRightloopLeft是否可以合并为一个函数。唯一的区别是“-=20”和“+=20”。 使用多态性,您可以进一步重构它。