单击后无法正确使用滚动功能

时间:2016-06-30 22:07:14

标签: javascript jquery scroll onclick

每当我在页面上滚动时,我创建了一个在li列表上递增类的函数,所以现在我想在点击上创建该函数但是存在冲突,例如,如果我点击并且我想要再次滚动增量功能停止,我该如何解决?



var scrollable = $('ul li').length - 1,
  count = 0,
  allowTransition = true;
$('body').bind('mousewheel', function(e) {

  if (allowTransition) {
    allowTransition=false;
    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;
      }

    }
    setTimeout(function() {
      allowTransition=true;
    }, 1000);
  }
});

$('ul li').on('click', function() {
  $('ul li').removeClass('active');
  $(this).addClass('active');
});

body{
  overflow:hidden;
  }

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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

这是一个工作脚本http://codepen.io/mozzi/pen/oLWZjY

您需要重置allowTransition标志并更新当前计数

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

    }
    setTimeout(function() {
      allowTransition=true;
    }, 1000);
  }
});

$('ul li').on('click', function() {
  $('ul li').removeClass('active');
  $(this).addClass('active');
  count = $(this).attr('count');
  allowTransition=true;
});
body{
  overflow:hidden;
  }

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" count='0'></li>
      <li count='1'></li>
      <li count='2'></li>
      <li count='3'></li>
    </ul>