刚开始学前端,记录下学到的知识,原生js实现拖拽弹性重力运行。记录下,直接上代码:
- html和css部分
<div></div>
div {
width: 100px;
height: 100px;
position: absolute;
left: 0;
top: 0;
background-color: chocolate;
border-radius: 50%;
}
- js部分
<script>
var oDiv = document.getElementsByTagName("div")[0];
var lastX = 0;
var lastY = 0;
var speedX = 0;
var speedY = 0;
oDiv.onmousedown = function (e) {
var self = this;
clearInterval(this.timer);
var event = e || window.event;
var disX = event.clientX - this.offsetLeft;
var disY = event.clientY - this.offsetTop;
document.onmousemove = function (e) {
self.style.left = e.clientX - disX + "px";
self.style.top = e.clientY - disY + "px";
speedX = self.offsetLeft - lastX;
speedY = self.offsetTop - lastY;
lastX = self.offsetLeft;
lastY = self.offsetTop;
}
document.onmouseup = function () {
document.onmousemove = null;
startMovee(self,speedX,speedY);
}
}
function startMovee(dom, speedX, speedY) {
clearInterval(dom.timer);
// 加速度和能量损失
var g = 3, e = 0.8;
dom.timer = setInterval(function () {
speedY += g;
var newTop = dom.offsetTop + speedY;
var newLeft = dom.offsetLeft + speedX;
var clientHeight = document.documentElement.clientHeight;
var clientWidth = document.documentElement.clientWidth;
if (newTop >= clientHeight - dom.clientHeight) {
speedY *= -1;
speedX *= e;
speedY *= e;
newTop = clientHeight - dom.clientHeight;
}
if (newTop <= 0) {
speedY *= -1;
speedX *= e;
speedY *= e;
newTop = 0;
}
if (newLeft >= clientWidth - dom.clientWidth) {
speedX *= -1;
speedX *= e;
speedY *= e;
newLeft = clientWidth - dom.clientWidth;
}
if (newLeft <= 0) {
speedX *= -1;
speedX *= e;
speedY *= e;
newLeft = 0;
}
//停止运动
if (Math.abs(speedY) < 1) {
speedY = 0;
}
if (Math.abs(speedX) < 1) {
speedX = 0;
}
if (speedX == 0 && speedY == 0 && dom.offsetTop <= (clientHeight - dom.clientHeight)) {
clearInterval(dom.timer);
} else {
dom.style.left = newLeft + "px";
dom.style.top = newTop + "px";
}
}, 30)
}
</script>