https://jsfiddle.net/wz9ghpnc/
使用:最新的jQuery
为什么在移动设备上这种情况滞后?尝试优化这一点我真的完成了。
如何应用反跳/节流之类的功能?我试图将setTimeout添加到具有50毫秒延迟的move()函数中,但这也太迟了。
在移动设备上移动太慢...动画太慢...
let $state = {
afterDown: {
clientX: 0,
scrollLeft: 0,
},
afterUp: {
clientX: 0,
scrollLeft: 0,
},
dreamedScrollLeft: 0,
isDown: false,
};
let centering = false;
let duration = 250;
let messages = false;
function message () {
if (messages === true) {
console.log('%c addScroll ', 'background: #000; color: #fff;', ...arguments);
}
}
// Events
function down (parent) {
return (event) => {
message('down');
if ($state.isDown === false) {
$state.afterDown.clientX = event.originalEvent.touches ? event.originalEvent.touches[0].clientX : event.clientX;
$state.afterDown.scrollLeft = $(parent).scrollLeft();
$(parent).stop();
$state.isDown = true;
}
};
}
function leave (parent) {
return () => {
message('leave');
if ($state.isDown === true) {
$(parent).removeClass('scroll-moving');
$state.isDown = false;
}
};
}
function move (parent) {
return (event) => {
message('move');
if ($state.isDown === true) {
$(parent).addClass('scroll-moving');
const clientX = event.originalEvent.touches ? event.originalEvent.touches[0].clientX : event.clientX;
$(parent).scrollLeft($state.afterDown.clientX + $state.afterDown.scrollLeft - clientX);
}
};
}
function scroll (parent) {
return () => {
message('scroll');
if (centering === true) {
if ($(parent).scrollLeft() === $state.dreamedScrollLeft) {
message('after scroll centering');
if (centering === true) {
if ($(parent).scrollLeft() === $state.dreamedScrollLeft) {
message('after scroll centering');
}
}
}
}
};
}
function up (parent) {
return (event) => {
message('up');
if ($state.isDown === true) {
$(parent).removeClass('scroll-moving');
$state.afterUp.clientX = event.originalEvent.changedTouches ? event.originalEvent.changedTouches[0].clientX : event.clientX;
$state.afterUp.scrollLeft = $(parent).scrollLeft();
if ($state.afterDown.clientX > $state.afterUp.clientX) {
message(' moving right');
$state.dreamedScrollLeft = $(parent).scrollLeft() + ($state.afterDown.clientX - $state.afterUp.clientX);
}
if ($state.afterUp.clientX > $state.afterDown.clientX) {
message(' moving left');
$state.dreamedScrollLeft = $(parent).scrollLeft() - ($state.afterUp.clientX - $state.afterDown.clientX);
}
$(parent).animate({ scrollLeft: $state.dreamedScrollLeft, }, duration, 'linear');
message($state.afterDown, $state.afterUp, $state.dreamedScrollLeft);
$state.isDown = false;
}
};
}
$.fn.extend({
addScroll: function (i) {
if (i.centering) {
centering = i.centering;
}
if (i.duration) {
duration = i.duration;
}
if (i.messages) {
messages = i.messages;
}
$(this).css('overflow', 'hidden');
$(this).bind('mousedown touchstart', down(this));
$(this).bind('mouseleave', leave(this));
$(this).bind('mousemove touchmove', move(this));
$(this).bind('scroll', scroll(this));
$(this).bind('mouseup touchend', up(this));
},
});