gpt4 book ai didi

javascript - 滑动删除javascript

转载 作者:行者123 更新时间:2023-11-28 19:21:02 31 4
gpt4 key购买 nike

我正在开发一个函数,当您向左滑动时,该函数将删除 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 吗?

最佳答案

是的,您只需计算 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 即可。

关于javascript - 滑动删除javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28909299/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com