注:浏览器f12,选择移动方式查看。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
touch-action: none;
}
html,
body {
width: 100%;
height: 100%;
}
#div1 {
width: 100px;
height: 100px;
background: cyan;
position: absolute;
bottom: 200px;
right: 100px;
}
</style>
</head>
<body>
<div id="div1"></div>
</body>
</html>
<script>
window.onload = function () {
// var moveNode = document.querySelector(".cus");
// moveNode.style.transform = 'translateX(400px)';
var div1 = document.querySelector("#div1");
//限制最大宽高,不让滑块出去
debugger
var maxW = document.body.clientWidth - div1.offsetWidth;
var maxH = document.body.clientHeight - div1.offsetHeight - 100;
var moveDirection = 0; //自动移动方向:+ 右移:- 左移
var moveDistance = 100; //自动移动距离
//手指触摸开始,记录div的初始位置
div1.addEventListener('touchstart', function (e) {
// if(div1.style.transition != ''){
// div1.style.transition = '';
// div1.style.transform = '';
// let direc = moveDirection == '+' ? '-' : '+';
// direc += moveDistance - 0;
// div1.style.left = ((div1.style.left + '').replace(/px/, '') - 0 + parseFloat(direc)) + 'px';
// }
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.opacity = '0.2'
div1.style.left = oLeft + 'px';
div1.style.top = oTop + 'px';
});
//触摸结束时的处理
div1.addEventListener('touchend', function () {
div1.style.opacity = '1'
moveDirection = div1.style.left.replace(/px/, '') - 0 + div1.offsetWidth / 2 > document.body.clientWidth / 2 ? '+' : '-';
moveDistance = moveDistance;
if(moveDirection == '+'){
moveDistance = document.body.clientWidth - div1.style.left.replace(/px/, '') - div1.offsetWidth;
}else{
moveDistance = div1.style.left.replace(/px/, '')
}
if(moveDistance > 0){
div1.style.transition = 'all .5s';
div1.style.transform = 'translateX(' + moveDirection + moveDistance + 'px)';
setTimeout(function() {
div1.style.left = div1.style.left.replace(/px/, '') - 0 + (moveDirection == '-' ? -moveDistance : moveDistance) + 'px'
div1.style.transition = '';
div1.style.transform = '';
}, 500)
}
document.removeEventListener("touchmove", defaultEvent);
});
//阻止默认事件
function defaultEvent(e) {
e.preventDefault();
}
// var ele = document.querySelector(".father");
// left_scroll(ele);
}
</script>
效果图:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。