注意事项:

1、pageX、pageY的兼容问题

2、使目标移动鼠标中间位置还必须减去盒子宽度的一半

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div {
width: 100px;
height: 100px;
background-color: #ccc;
position: absolute;
}
</style>
</head>
<body>
<div></div>
<script>
var divEle = document.getElementsByTagName("div")[0];
var timer = null;
document.onclick = function (ev) {
ev = ev || window.event;
console.log(ev);
var pageX = ev.pageX || scroll().left + ev.clientX;
var pageY = ev.pageY || scroll().top + ev.clientY;
animateX(divEle, pageX - 50, pageY - 50);
} function animateX(ele, targetX, targetY) {
clearInterval(timer);
timer = setInterval(function () {
var stepX = (targetX - ele.offsetLeft) / 10;
stepX = stepX > 0 ? Math.ceil(stepX) : Math.floor(stepX);
ele.style.left = ele.offsetLeft + stepX + "px";
console.log(1);
var stepY = (targetY - ele.offsetTop) / 10;
stepY = stepY > 0 ? Math.ceil(stepY) : Math.floor(stepY);
ele.style.top = ele.offsetTop + stepY + "px"; if (Math.abs(targetX - ele.offsetLeft) <= Math.abs(stepX) && Math.abs(targetY - ele.offsetTop) <= Math.abs(stepY)) {
ele.style.left = targetX + "px";
ele.style.top = targetY + "px";
clearInterval(timer);
}
}, 15);
} function scroll() {
return {
"top": window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop,
"left": window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft
};
}
</script>
</body>
</html>
05-26 18:33