【问题标题】:Get each scroll and increment active class获取每个滚动并增加活动类
【发布时间】:2016-06-28 20:07:25
【问题描述】:

我想在鼠标滚轮事件上创建一个自定义滑块,我的问题是如何在我的页面上完成每个滚动并在我的“ul li”上添加一个活动类并逐个递增它,例如:

if ($('scroll') === 1, function() {
  $('ul li:first-child').addClass('active');
});
if ($('scroll') === 2, function() {
  $('ul li:nth-child(2)').addClass('active');
});
ul li{
  height:20px;
  width:20px;
  background:blue;
  margin:5px;
  list-style:none
  }

ul li.active{
  background:red;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="active"></li>
  <li></li>
  <li></li>
  <li></li>
</ul>

【问题讨论】:

  • 您尝试使用的这种奇怪的语法到底是什么?第 1 步是解决这个问题。

标签: javascript jquery scroll mousewheel


【解决方案1】:

基于this answer:,你可以这样做:

var scrollable = $('ul li').length - 1,
  count = 0;
$('body').bind('mousewheel', function(e) {
  if (e.originalEvent.wheelDelta / 120 > 0) {
    if (scrollable >= count && count > 0) {
      $('.active').removeClass('active').prev().addClass('active');
      count--
    } else {
      return false;
    }
  } else {
    if (scrollable > count) {
      $('.active').removeClass('active').next().addClass('active');
      count++
    } else {
      return false;
    }

  }
})
ul li {
  height: 20px;
  width: 20px;
  background: blue;
  margin: 5px;
  list-style: none
}
ul li.active {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="active"></li>
  <li></li>
  <li></li>
  <li></li>
</ul>

【讨论】:

    【解决方案2】:

    此语法无效:

    if (value === other value, function() {
    
    });
    

    if 语句的正确语法如下:

    if (value === other value) {
        // execute code in here
    }
    

    另外,你有这个:

    $('scroll') === 1
    

    这里,$('scroll') 是一个选择 &lt;scroll&gt; HTML 元素(不存在)的 jQuery 函数。

    相反,您可以在 JavaScript 中使用 window.scrollY 检测页面的滚动位置,它会返回 the number of pixels that the document is currently scrolled down from the top。例如:

    if (window.scrollY < 100) {
        $('ul li:first-child').addClass('active');
    } else if (window.scrollY < 200) {
        $('ul li:nth-child(2)').addClass('active');
    }
    

    【讨论】:

    • 谢谢,但是每次用户在页面中滚动时都没有可能获得?不是像素,而是每次他使用鼠标滚轮时?如果正文溢出被隐藏,我认为您的解决方案将无法工作
    • 您可以将add an event listener 换成"scroll" event
    猜你喜欢
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    相关资源
    最近更新 更多