示例代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JS惯性拖拽</title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
font-family: "微软雅黑", "张海山锐线体简"
}
#div1 {
width: 200px;
height: 200px;
position: absolute;
background-color: #0000FF;
left: 0;
top: 0;
}
.box {
width: 10px;
height: 10px;
background: green;
position: absolute;
left: 0;
top: 0;
}
</style>
<script>
let screenX = 0;
let screenY = 0;
window.onload = function() {
watchChangeSize();
//被移动物 相关方法 start
var oDiv = document.getElementById('div1');
oDiv.onmousedown = function(ev) {
var speedX = 0,
speedY = 0; //要求的速度
var lastX = 0,
lastY = 0; //最后一次的距离
var oEvt = ev || event;
var disX = oEvt.clientX - oDiv.offsetLeft;
var disY = oEvt.clientY - oDiv.offsetTop;
document.onmousemove = function(ev) {
// console.log("鼠标移动。。。仅触发一次 funcStart")
// console.log(ev)
// console.log("鼠标移动。。。仅触发一次 funcEnd")
// console.log("===========分割线============")
var oEvt = ev || event;
oDiv.style.left = oEvt.clientX - disX + 'px';
oDiv.style.top = oEvt.clientY - disY + 'px';
speedX = oDiv.offsetLeft - lastX
speedY = oDiv.offsetTop - lastY
lastX = oDiv.offsetLeft
lastY = oDiv.offsetTop
};
document.onmouseup = function() {
document.onmousemove = document.onmouseup = null;
move(oDiv, speedX, speedY);
};
return false;
};
function move(obj, speedX, speedY) {
clearInterval(obj.timer);
obj.timer = setInterval(function() {
speedX *= 0.95 //摩擦
speedY *= 0.95 //摩擦
let tempDoneX = obj.offsetLeft + speedX; //临时的最终X轴坐标
if (tempDoneX < 0) {
tempDoneX = 0
} else if ((tempDoneX+parseInt(obj.style.width)) > screenX) {
tempDoneX = screenX - parseInt(obj.style.width);
clearInterval(obj.timer);
}
obj.style.left = tempDoneX + 'px';
let tempDoneY = obj.offsetTop + speedY;
if (tempDoneY < 0) {
//Y轴坐标小于0,赋值为0;
tempDoneY = 0
} else if ((tempDoneY+parseInt(obj.style.height)) > screenY) {
tempDoneY = screenY - parseInt(obj.style.height);
clearInterval(obj.timer);
}
obj.style.top = tempDoneY + 'px';
if (Math.abs(speedX) < 1 ) speedX = 0;
if (Math.abs(speedY) < 1 ) speedY = 0;
if (speedX == 0 && speedY == 0) {
clearInterval(obj.timer);
}
}, 30);
}
// 被移动物 相关方法 end
};
window.onresize = function() {
// console.log('监听变化')
watchChangeSize();
}
function watchChangeSize() {
//可视区的宽/高(DOM)
//offsetHeight(带边框)和clientHeight(不带边框)区别参考上一篇文章
var offsetWid = document.documentElement.clientWidth;
var offsetHei = document.documentElement.clientHeight;
screenX = offsetWid;
screenY = offsetHei;
}
</script>
</head>
<body>
<div id="div1" style="width: 100px; height: 100px; background-color: black;"></div>
</body>
</html>