【发布时间】:2020-09-10 07:38:17
【问题描述】:
我在按钮“onmousedown”上绑定了一个函数,它模拟了通过 div 滚动。多次快速点击和按住太久会出现问题。
例如,如果用户滚动到 div 的底部,并快速点击多次“向下”按钮,则 div 内的 OL 上下抖动非常快(快于 33ms,这是最快的滚动速度)可能的)。我相信它会创建多个计时器对象,每个对象都会滚动 div 而不会清除这些对象?
另一个问题是,如果按钮被按住太久并被释放,它的行为就像按钮仍然被按住一样。 (以 33 毫秒的速率滚动)。一旦鼠标从按钮上抬起,似乎忘记删除计时器对象
要解决第二个问题,用户必须在与滚动相反的方向上单击一次按钮,它又会变成静止的。
这是里面需要滚动的div
function scrollButton(btn, start, speedUp, eDiv, upward) {
var tempStart = start;
var repeat = function () {
//check for boundary conditions
if (eDiv.scrollTop >= 0 && eDiv.scrollTop <= (eDiv.scrollHeight - eDiv.clientHeight)) {
scrollErrorLog(eDiv, upward);
}
//fire scroll method and reduce time interval
t = setTimeout(repeat, start);
if (start > 60) {
start = Math.round(start / speedUp);
} else start = 33;
}
//bind functions to button events
btn.onmousedown = function () {
repeat();
}
btn.onmouseup = function () {
clearTimeout(t);
start = tempStart;
}
btn.onmouseout = function () {
clearTimeout(t);
start = tempStart;
}
btn.ontouchcancel = function () {
clearTimeout(t);
start = tempStart;
}
btn.ontouchend = function () {
clearTimeout(t);
start = tempStart;
}
btn.ontouchstart = function () {
repeat();
}
}
var scrollErrorLog = function (eDiv, upward) {
//calculate maximum scroll height
var maxScrollHeight = eDiv.scrollHeight - eDiv.clientHeight;
//how much scroll in one button click iteration
var jumpSize = 40;
//going up or down?
if (upward) {
if (eDiv.scrollTop > 0) {
scrollTimes--;
}
} else {
if (eDiv.scrollTop < maxScrollHeight) {
scrollTimes++;
}
}
//scroll the div
if (eDiv.scrollTop >= 0 && eDiv.scrollTop <= maxScrollHeight) {
eDiv.scrollTop = scrollTimes * jumpSize;
}
// if out of bounds, return to start position and reset scrollTimes tracker variable
if (eDiv.scrollTop < 0 || scrollTimes < 0) {
eDiv.scrollTop = 0;
scrollTimes = 1;
} else if (eDiv.scrollTop > maxScrollHeight) {
eDiv.scrollTop = maxScrollHeight;
scrollTimes = maxScrollHeight / jumpSize;
}
}
编辑:我以这个问题为指导:Need javascript code for button press and hold
编辑#2:这需要主要在触摸上工作。在按钮上单击它有时会这样做,有时不会。在触摸屏上,它会不断出现这 2 个错误。
【问题讨论】:
标签: javascript button scroll timer