javascript - 重新安排 js 以适应更多灵活性

标签 javascript jquery html parent

如何使此 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/

最佳答案

所以在这里,我“合并”了两个箭头处理程序。
然后,需要根据要滚动的宽度进行计算来确定“滚动”速度,该宽度可能并不总是元素宽度的 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

关于javascript - 重新安排 js 以适应更多灵活性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44656776/

相关文章:

jquery - HTML5 旋转 Logo

javascript - 定时内容容器 Javascript

php - 如何在jquery对话框中显示php提交表单的结果

javascript - cookie - 只投票一次

html - CSS3 进度条 - 使用 span 来定义进度量

javascript - 如何在带下划线的哈希中找到最小值的键

javascript - 自动从 Gmail 帐户垃圾邮件文件夹中删除包含特定关键字的电子邮件

javascript - react : TypeError: Cannot call a class as a function

javascript - 输入 - 移动浏览器上仅输入数字

html - 像其他浏览器高度一样设置 div 高度