参考博客:
https://www.cnblogs.com/hpuzy0127/p/5073844.html
https://blog.csdn.net/u012468376/article/details/72808761
这次的大作业里面想用 touch事件 做一个在移动端可以拖拽的小图标,嘿嘿,但是还没用到过,然后就参考学习了它的用法。下面就记录下实现此功能的代码吧~
总的来说 移动端的touch事件 和 PC端的移动拖拽事件的原理一样:
touchstart事件(当在屏幕上按下手指时触发) ———— onmusedown
touchmove事件(当在屏幕上移动手指时触发) ———— onmusedown
touchend事件(当在屏幕上抬起手指时触发,下面代码中没有用到它也能实现触摸拖拽效果) ———— onmuseup
<!--移动端 提示小图标-->
<img src="img/tips4.png" alt="" class="mobile-tips-icon none">
/*提示图标*/
.mobile-tips-icon{
display: inline-block;
width: 35px;
height: 35px;
position: absolute; //脱离文档流
top: 480px;
left: 2px;
z-index: 99999;
}
/**** touch事件 ——> 手机端拖拽提示图标 ****/
var imgObj = document.getElementsByClassName('mobile-tips-icon')[0]; //获取可拖动元素
var stratX, startY, startPositionX, startPositionY;
//touchstart事件
function touchSatrtFunc(e) {
var e = e || window.event;
// e.preventDefault(); //阻止触摸时浏览器的缩放、滚动条滚动等
var touch = e.touches[0]; //获取第一个触点
var x = Number(touch.pageX); //页面触点X坐标
var y = Number(touch.pageY); //页面触点Y坐标
//记录触点初始位置
startX = x;
startY = y;
//可拖动元素距离页面顶部的距离
startPositionY = imgObj.offsetTop;
//可拖动元素距离页面左侧的距离
startPositionX = imgObj.offsetLeft;
}
//touchmove事件
function touchMoveFunc(e) {
var e = e || window.event;
// e.preventDefault(); //阻止触摸时浏览器的缩放、滚动条滚动等
var touch = e.touches[0]; //获取第一个触点
var x = Number(touch.pageX); //页面触点X坐标
var y = Number(touch.pageY); //页面触点Y坐标
let left = startPositionX + (x - startX);
let top = startPositionY + (y - startY);
//横向最大可移动距离
let moveMaxW = document.body.clientWidth - imgObj.offsetWidth;
//纵向最大可移动距离
let moveMaxH = document.body.clientHeight - imgObj.offsetHeight;
left = left < 0 ? 0 : left;
left = left > moveMaxW ? moveMaxW : left;
top = top < 0 ? 0 : top;
top = top > moveMaxH ? moveMaxH : top;
imgObj.style.left = left + 'px';
imgObj.style.top = top + 'px';
}
imgObj.addEventListener('touchstart', touchSatrtFunc, false);
imgObj.addEventListener('touchmove', touchMoveFunc, false);
imgObj.addEventListener('click', function () {
$(this).hide();
$(".tips-content-wrap").fadeIn(500);
});
$(".tips-content-wrap .close").click(function () {
$(".tips-content-wrap").fadeOut();
$(".mobile-tips-icon").show();
});