我正在开发一个功能,当你向左滑动时会删除div ...
这是一个我想在刷卡时删除的div:
<div class="listItem">Stuff here</div>
我有javascript来确定我使用touchstart和touchend事件监听器刷过页面的位置。
我创建了一个名为删除项目的函数:
function swipeLeft(){
//delete item
}
我正在确定我在哪里滑动:
var touchobj = e.changedTouches[0];
dist = touchobj.pageX - startX
现在是否可以使用此信息删除div?
答案 0 :(得分:2)
是的,你只计算div的大小和滑动距离之间的增量。
以下是通用滑动模式检测的一个很好的示例:
http://www.javascriptkit.com/javatutors/touchevents2.shtml
代码:
function swipedetect(el, callback){
var touchsurface = el,
swipedir,
startX,
startY,
distX,
distY,
threshold = 150, //required min distance traveled to be considered swipe
restraint = 100, // maximum distance allowed at the same time in perpendicular direction
allowedTime = 300, // maximum time allowed to travel that distance
elapsedTime,
startTime,
handleswipe = callback || function(swipedir){}
touchsurface.addEventListener('touchstart', function(e){
var touchobj = e.changedTouches[0]
swipedir = 'none'
dist = 0
startX = touchobj.pageX
startY = touchobj.pageY
startTime = new Date().getTime() // record time when finger first makes contact with surface
e.preventDefault()
}, false)
touchsurface.addEventListener('touchmove', function(e){
e.preventDefault() // prevent scrolling when inside DIV
}, false)
touchsurface.addEventListener('touchend', function(e){
var touchobj = e.changedTouches[0]
distX = touchobj.pageX - startX // get horizontal dist traveled by finger while in contact with surface
distY = touchobj.pageY - startY // get vertical dist traveled by finger while in contact with surface
elapsedTime = new Date().getTime() - startTime // get time elapsed
if (elapsedTime <= allowedTime){ // first condition for awipe met
if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint){ // 2nd condition for horizontal swipe met
swipedir = (distX < 0)? 'left' : 'right' // if dist traveled is negative, it indicates left swipe
}
else if (Math.abs(distY) >= threshold && Math.abs(distX) <= restraint){ // 2nd condition for vertical swipe met
swipedir = (distY < 0)? 'up' : 'down' // if dist traveled is negative, it indicates up swipe
}
}
handleswipe(swipedir)
e.preventDefault()
}, false)
}
//USAGE:
/*
var el = document.getElementById('someel')
swipedetect(el, function(swipedir){
swipedir contains either "none", "left", "right", "top", or "down"
if (swipedir =='left')
alert('You just swiped left!')
})
*/
如果需要,您只需调整阈值即可。一旦检测到,您只需从DOM中删除div。