我想创建一个页面和一个部分的网站。该部分上有一个分页,当鼠标向上/向下滚动时,该分页将更改页面。
我尝试实现鼠标滚轮事件,但该事件不仅触发了多次,而且一次滚动/上滚事件会多次更改我的页码。 我已经检查了滚动和鼠标滚轮事件,但是每个事件不仅会一次触发该事件,还会在一个滚动事件上多次触发该事件
var page = 1;
$(window).bind('mousewheel', function(event) {
if (event.originalEvent.wheelDelta >= 0) {
$('#page-number').html(page++);
console.log('Scroll up');
} else {
$('#page-number').html(page--);
console.log('Scroll down');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Page <span id="page-number">1</span></div>
我希望当鼠标上下滚动不多次时,页面只会改变一次。
答案 0 :(得分:2)
您可以使用debounce中的throttle或lodash.js函数。
示例:
let page = 1;
const mouseWheelHandler = (event) => {
if (event.originalEvent.wheelDelta >= 0) {
$('#page-number').html(page++);
console.log('Scroll up');
} else {
$('#page-number').html(page--);
console.log('Scroll down');
}
}
// will be called in a half of second after user stops to scroll
$(window).bind('mousewheel', _.debounce((event) => mouseWheelHandler(event), 500));
// will be called once in a second while user keeps scrolling
// $(window).bind('mousewheel', _.throttle((event) => mouseWheelHandler(event)), 1000));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
<div>Page <span id="page-number">1</span></div>
答案 1 :(得分:0)
var page = 1;
var currentDirection;
$(window).bind('mousewheel', function(event) {
if (currentDirection !== 'up' && event.originalEvent.wheelDelta >= 0) {
currentDirection = 'up';
$('#page-number').html(page++);
console.log('Scroll up');
} else if (currentDirection !== 'down') {
currentDirection = 'down';
$('#page-number').html(page--);
console.log('Scroll down');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Page <span id="page-number">1</span></div>