今天小编给大家带来JS实现移动端触屏拖拽功能的教程
1.html部分
2.css部分
* {
margin: 0;
padding: 0;
}
html,
body {
width: 100%;
height: 100%;
}
#div1 {
width: 50px;
height: 50px;
background: cyan;
position: absolute;
}
|
3.js部分
var div1 = document.querySelector('#div1');
//限制最大宽高,不让滑块出去
var maxW = document.body.clientWidth - div1.offsetWidth;
var maxH = document.body.clientHeight - div1.offsetHeight;
//手指触摸开始,记录div的初始位置
div1.addEventListener('touchstart', function(e) {
var ev = e || window.event;
var touch = ev.targetTouches[0];
oL = touch.clientX - div1.offsetLeft;
oT = touch.clientY - div1.offsetTop;
document.addEventListener("touchmove", defaultEvent, false);
});
//触摸中的,位置记录
div1.addEventListener('touchmove', function(e) {
var ev = e || window.event;
var touch = ev.targetTouches[0];
var oLeft = touch.clientX - oL;
var oTop = touch.clientY - oT;
if(oLeft < 0) {
oLeft = 0;
} else if(oLeft >= maxW) {
oLeft = maxW;
}
if(oTop < 0) {
oTop = 0;
} else if(oTop >= maxH) {
oTop = maxH;
}
div1.style.left = oLeft + 'px';
div1.style.top = oTop + 'px';
});
//触摸结束时的处理
div1.addEventListener('touchend', function() {
document.removeEventListener("touchmove", defaultEvent);
});
//阻止默认事件
function defaultEvent(e) {
e.preventDefault();
}
|
效果图如下:
4.重要说明
对于触屏手机端用手指事件,对于PC端用鼠标事件,原理都一样。大家自己去试试吧!