标签:touchend touchstart JavaScript touchmove touch console event
JavaScript touch 事件 touchstart touchmove touchend
MDN 官方文档: https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
一、touch 事件有哪些
页面中的 touch
事件一般在移动端使用,pc
端是没有效果的。
touch
相关的事件有四个
touchstart
触摸开始touchmove
触摸移动中touchend
触摸结束touchcancel
触摸取消
二、如何使用
只需要给你需要添加触摸方法的 dom
元素添加对应的事件监听即可。
具体的操作需要根据 event
中的属性来操作,后面细说。
document.addEventListener('touchstart', event => {
console.log('touchstart')
}, false)
document.addEventListener('touchmove', event => {
console.log('touchmove')
}, false)
document.addEventListener('touchend', event => {
console.log('touchend')
}, false)
二、相关的对象,用到的事件属性
先来看一下事件 event 的一些属性:
在 touchstart
和 touchmove
的 event
里面都会有一个 touches
对象,这是个数组,记录了触摸的个数和对应的在页面中的位置。而在 touchend
中就没有这个 touches
对象。
看一下 touches
对象的具体属性:
所以我们在方法中就能实时获取当前触摸的位置,有了 x
y
就可以做我们想做的事了。
三、实现一个触摸移动 dom 元素的实例
做一个页面,页面里面有 n 个方块,手机上拖动方块可以移动其位置。
我们需要做的:
body
的position
定义为relative
,方块的position
定义为absolute
- 然后给 documnet 添加那三个 touch 事件:
touchstart
touchmove
touchend
- 在方法内部,判断被触摸的元素是不是方块,避免把 body 也拖动了。如果是方块就拖动,如果不是就不拖动。
window.onload = () => {
$('body').style.height = window.innerHeight + 'px';
init();
}
function init(){
document.addEventListener('touchstart', event => {
console.log(event);
let touch = event.touches[0];
console.log('start:', touch.pageX, touch.pageY)
}, false)
document.addEventListener('touchmove', event => {
// 只移动 .square dom
if (event.target.classList.contains('square')){
let touch = event.touches[0];
console.log('move:', touch.pageX, touch.pageY)
move(event.target, touch);
}
}, false)
document.addEventListener('touchend', event => {
console.log('end:')
}, false)
}
function move(item, touch){
let width = item.offsetWidth;
let height = item.offsetHeight;
item.style.left = touch.pageX - width/2 + 'px';
item.style.top = touch.pageY - height/2 + 'px';
}
function $(selector){
return document.querySelector(selector)
}
四、效果
标签:touchend,touchstart,JavaScript,touchmove,touch,console,event 来源: https://blog.csdn.net/KimBing/article/details/110470502
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。