touchmover手机移动端的拖动

时间:2021-10-08 15:17:32

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title></title>
<script src="js/mui.min.js"></script>
<link href="css/mui.min.css" rel="stylesheet" />
<style>
#touch {
width: 50px;
height: 50px;
position: absolute;
left: 100px;
top: 200px;
margin-left: -30px;
margin-top: -30px;
z-index: 999999;
}

#simple-menu {
cursor: move;
}
</style>
</head>
<body>
<header class="mui-bar mui-bar-nav">
<h1 class="mui-title">可拖动悬浮小球</h1>
</header>
<div class="mui-content">
<div id="touch" style="width: 50px; height: 50px; position: absolute;">
<img id="simple-menu" src="huli.png" style="width: 50px; height: 50px;" />
</div>
</div>
<script>
mui.init({
swipeBack: true //启用右滑关闭功能
});
var div = document.getElementById('touch');
var viewWidth = window.screen.width;
var viewHeight = window.screen.height;
var divWidth = parseInt(div.style.width);
var divHeight = parseInt(div.style.height);
div.addEventListener('touchmove', function(event) {
event.preventDefault(); //阻止其他事件
// 如果这个元素的位置内只有一个手指的话
if(event.targetTouches.length == 1) {
var touch = event.targetTouches[0]; // 把元素放在手指所在的位置
var tempWidth = touch.pageX;//存储x坐标
var tempHeigth = touch.pageY;//存储Y坐标
if((touch.pageX + divWidth) > viewWidth) {//超越右边界
tempWidth = viewWidth - divWidth/2;
}
if((touch.pageY + divHeight) > viewHeight) {//超越下边界
tempHeigth = viewHeight - divHeight;
}
if((touch.pageX - divWidth)<0){//超越左边界
tempWidth=divWidth/2;
}
if((touch.pageY - divHeight)<0){//超越上边界
tempHeigth=divHeight/2;
}
div.style.left = tempWidth + 'px';
div.style.top = tempHeigth + 'px';
div.style.background = "";
}
}, false);
</script>
</body>

</html>