gpt4 book ai didi

javascript - 动画元素到鼠标光标

转载 作者:行者123 更新时间:2023-12-03 06:59:31 25 4
gpt4 key购买 nike

我必须移动我创建的元素 onmousedown到光标方向onmouseup并为整个事物设置动画。

/*
function to spawn the ball
@param {event} event: onclick event
*/

var isDown = false;
var isDrag = false;

/*
function to get the position of the cursor on mouse down
@param {mousedown} event
*/
document.body.onmousedown = function (mousedown) {
downX = mousedown.offsetX;
downY = mousedown.offsetY;
isDraggring = true;

/*
function to check if the user is dragging or clicking
*/
document.body.onmousemove = function () {
if (isDraggring) isDrag = true;

/*
function to detect the the mouse up event
@param {mouseup} event
*/
document.body.onmouseup = function (mouseup) {
if (isDrag) {
var ball = document.createElement("p");
ball.innerHTML = "ball";
document.body.append(ball);
ball.style.position = "absolute";
ball.style.left = downX - ball.offsetWidth / 2 + "px";
ball.style.top = downY - ball.offsetHeight / 2 + "px";
}
};
};
};

如果位置在相同的高度并且没有 Angular ,那就是:ball.style.left/top=mouseup.offsetX/Y 但因为大多数时候都有一个小 Angular 事件我不知道如何使“球”向那个方向移动。
此外,球在到达光标后不应停止。
有什么帮助吗?

最佳答案

我采取了最简单的方法,只需保存 mouse-up事件坐标,然后把球带到那里。
如果你需要继续这个动画:你已经得到了 mouse-downmouse-up事件坐标,你可以计算这些点之间的斜率,你就会知道你想要前进的方向。

/*
function to spawn the ball
@param {event} event: onclick event
*/

var isDown = false;
var isDrag = false;

/*
function to get the position of the cursor on mouse down
@param {mousedown} event
*/
document.body.onmousedown = function (mousedown) {
downX = mousedown.offsetX;
downY = mousedown.offsetY;
isDraggring = true;

/*
function to check if the user is dragging or clicking
*/
document.body.onmousemove = function () {
if (isDraggring) isDrag = true;

/*
function to detect the the mouse up event
@param {mouseup} event
*/
document.body.onmouseup = function (mouseup) {
if (isDrag) {
var ball = document.createElement("p");
ball.className = "ball";
ball.innerHTML = "ball";
document.body.append(ball);
ball.style.position = "absolute";
ball.style.left = downX - ball.offsetWidth / 2 + "px";
ball.style.top = downY - ball.offsetHeight / 2 + "px";

setTimeout(()=>{
ball.style.left = mouseup.clientX + "px";
ball.style.top = mouseup.clientY + "px";
}, 500);
}
};
};
};
body{
width: 100vw;
height: 100vh;
margin: 0;
}

.ball{
transition: 0.5s;
}

关于javascript - 动画元素到鼠标光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64090371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com