<div style="width: 500px;height: 400px;background-color: lavender;margin-left:40px;margin-top:30px;" id="parent">
<div style="width: 30px;height: 30px;border-radius: 50%;background-color: lightpink;" id="child"></div>
</div>
window.addEventListener("DOMContentLoaded", (event) => {
const parent = document.querySelector("#parent");
const child = document.querySelector("#child");
let xTo = gsap.quickTo(child, "x", { duration: 0.4, ease: "power3" });
let yTo = gsap.quickTo(child, "y", { duration: 0.4, ease: "power3" });
// 从固定值到x 200的动画
// xTo(200)
// 从500->100 的动画
// xTo(100, 500)
const offsetX = parent.getBoundingClientRect().x;
const offsetY = parent.getBoundingClientRect().y;
const width = parent.getBoundingClientRect().width;
const height = parent.getBoundingClientRect().height;
const childWidth = child.getBoundingClientRect().width;
const childHeight = child.getBoundingClientRect().height;
parent.addEventListener("mousemove", (e) => {
let x = e.pageX - offsetX - childWidth / 2;
let y = e.pageY - offsetY - childHeight / 2;
let leftBound = width - childWidth;
let bottomBound = height - childHeight;
console.log(childWidth, bottomBound);
if (x <= 0) {
x = 0;
} else if (x > leftBound) {
x = leftBound;
}
if (y <= 0) {
y = 0;
} else if (y > bottomBound) {
y = bottomBound;
}
xTo(x);
yTo(y);
});
});
This Pen doesn't use any external CSS resources.