<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello MUI</title>
<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
<!--标准mui.css-->
<link rel="stylesheet" href="../css/mui.min.css">
</head>
<body>
<div id="div" style="width: 200px; height: 200px; background-color: #f00; position: absolute; right: 10px; bottom: 20px;"></div>
</body>
<script src="../js/mui.min.js"></script>
<script>
mui.init({
drag: true, //默认为true
});
var x = 0;
var y = 0;
var l = 0;
var t = 0;
var isDown = false;
var dv = document.getElementById("div");
document.querySelector('#div').addEventListener('dragstart',function(e){
console.log(e)
//获取x坐标和y坐标
x = e.detail.center.x;
y = e.detail.center.y;
//获取左部和顶部的偏移量
l = dv.offsetLeft;
t = dv.offsetTop;
//开关打开
isDown = true;
//设置样式
dv.style.cursor = 'move';
});
document.querySelector('#div').addEventListener('drag',function(e){
if (isDown == false) {
return;
}
//获取x和y
var nx = e.detail.center.x;
var ny = e.detail.center.y;
//计算移动后的左偏移量和顶部的偏移量
var nl = nx - (x - l);
var nt = ny - (y - t);
dv.style.left = nl + 'px';
dv.style.top = nt + 'px';
})
document.querySelector('#div').addEventListener('dragend',function(e){
//开关关闭
isDown = false;
dv.style.cursor = 'default';
})
</script>
</html>