我有以下代码,可让我滑动一个元素,该元素将移动,露出下面的元素。我希望能够滑动一次,运行功能,使div重置其位置,并允许我再次滑动。基本上,在功能运行时禁用滑动,然后在功能结束后将其启用。
这是我的代码:
var threshold = {
x: 30,
y: 10
}
var originalCoord = {
x: 0,
y: 0
}
var finalCoord = {
x: 0,
y: 0
}
function touchMove(event) {
finalCoord.x = event.targetTouches[0].pageX
changeX = originalCoord.x - finalCoord.x
var changeY = originalCoord.y - finalCoord.y
if (changeY < threshold.y && changeY > (threshold.y * -1)) {
changeX = originalCoord.x - finalCoord.x
if (changeX > threshold.x) {
// My function which runs when you swipe left
}
}
}
function touchEnd(event) {
}
function touchStart(event) {
originalCoord.x = event.targetTouches[0].pageX
finalCoord.x = originalCoord.x
}
window.addEventListener("touchstart", touchStart, false);
window.addEventListener("touchmove", touchMove, false);
window.addEventListener("touchend", touchEnd, false);
我认为一旦函数运行,我可以使用
event.preventDefault()
或return false
禁用拖动,但是最终仍然允许我在其中拖动。 最佳答案
很难弄清楚您想要什么,但是要禁用滑动,只需添加helper变量:
var _swipeDisabled = false;
然后在touchmove中检查是否禁用了滑动,如果是,则仅
return false
:function touchMove(event) {
if (_swipeDisabled) return false; // this line is crucial
finalCoord.x = event.targetTouches[0].pageX
changeX = originalCoord.x - finalCoord.x
var changeY = originalCoord.y - finalCoord.y
if (changeY < threshold.y && changeY > (threshold.y * -1)) {
changeX = originalCoord.x - finalCoord.x
if (changeX > threshold.x) {
_swipeDisabled = true; // add this before calling your function
// My function which runs when you swipe left
}
}
}
并且在您的功能中,您将不得不再次启用滑动,所以只需执行以下操作:
_swipeDisabled = false;
在您在那里调用的函数中。最简单的解决方案通常是最好的,请记住!