我有以下代码,它允许我滑动一个元素,该元素将移动,露出下面的元素。我希望能够滑动一次,运行该函数,让 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
在函数运行后禁用拖动,但它最终仍然允许我在运行期间拖动。
最佳答案
很难弄清楚你想要什么,但要禁用滑动只需添加辅助变量:
var _swipeDisabled = false;
然后在 touchmove 中检查是否禁用了滑动,如果是,则返回 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;
在您调用的函数中。最简单的解决方案通常是最好的,记住!
关于javascript - 第一次滑动后禁用滑动,完成后重置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12940139/