滑动以删除iOS中的JavaScript按钮? [英] Swipe to delete button for iOS in Javascript?
问题描述
我刚刚在Safari上的iPod上使用Facebook,无论何时您使用Messenger,并且在任何消息上向右/左滑动,都会出现删除按钮。
I was just on Facebook on my iPod in Safari and whenever you are in messenger and you swipe to the right/left on any message a delete button comes up.
有人可以引导我并告诉我它是如何在html / JS / jQuery中完成的?
Can someone guide me and possible tell me how it's done in html/JS/jQuery?
很多!
推荐答案
我不知道jQuery手机,这将是一个更简单的方法来做到这一点,但这里是你可以用普通的'JS'来完成它:
I don't know about jQuery mobile, which would be an easier way to do this, but here's how you can do it in plain ol' JS:
document.body.addEventListener('touchstart',function(e)
{
e = e || window.event;//don't know how mobile browsers behave here
var startCoordinates = {x:e.changedTouches[0].clientX,
y:e.changedTouches[0].clientY};
var endHandler = function(e)
{
e = e || window.e;
var xDiff = Math.abs(Math.abs(startCoordinates.x) -
Math.abs(e.changedTouches[0].clientX));
//unbind handler, avoid double listeners
document.body.removeEventListener('touchend', endHandler, false);
if (xDiff >= 50)
{//assume small movement wasn't intended as swipe
//here a swipe was detected
if (confirm('Are you sure you want to delete X?'))
{//perform xhr request here, or whatever
}
}
};
document.body.addEventListener('touchend',endHandler,false);
},false);
jQmobile可能会容易得多,但这是我认为的基本概念,适用于所有移动浏览器我已经为(Android,iOS(4到6))编写脚本,甚至在支持触摸事件的开发模式下使用chrome也可以使用这样的代码)。
jQmobile will probably be a lot easier, but this is the basic idea I think, that works on all mobile browsers I've written scripts for (Android, iOS (4 through 6), even chrome in dev-mode supporting touch events works with code like this).
更新:
增加了代码,专门处理滑动操作:
Update:
Added code, that deals with swipes specifically:
(function(G,und)
{
'use strict';
var load = function()
{
var tStart, body = document.body;
tStart = function(e)
{
e = e || G.event;
var coords = e.changedTouches[0].clientX,
tEnd = function(e)
{
e = e || G.event;
var currentX = e.changedTouches[0].clientX;
if (body.removeEventListener)
{
body.removeEventListener('touchend',tEnd,false);
}
else
{//shouldn't be possible, but I don't know all browsers, of course
body.detachEvent('ontouchend',tEnd);
}
if ((coords - currentX) <= 50)
{//too little movement
/*console.log*/alert('moved, but no real swipe');
}
else
{
/*console.log*/alert('SWIIIPEEE!');
}
};
if (body.addEventListener)
{
return body.addEventListener('touchend',tEnd,false);
}
body.attachEvent('ontouchend',tEnd);
};
if (G.removeEventListener)
{
body.addEventListener('touchstart',tStart,false);
return G.removeEventListener('load',load,false);
}
body.attachEvent('ontouchstart',tStart);
return G.detachEvent('onload',load);
};
if (G.addEventListener)
{
return G.addEventListener('load',load,false);
}
return G.attachEvent('onload',load);
}(this));
这篇关于滑动以删除iOS中的JavaScript按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!