gpt4 book ai didi

jquery - 将 div 旋转到鼠标位置

转载 作者:行者123 更新时间:2023-11-28 16:18:32 26 4
gpt4 key购买 nike

我想让一个div旋转到鼠标所在的位置,

所以当我的鼠标离开时它必须显示 <-当我的鼠标在右边时,它必须显示 ->

这需要在任何方向!

有没有人有解决办法?

编辑:

<style>
body {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
</style>

<div id="arrow">&gt;</div>

<script type="text/javascript">
var arrow = document.querySelector("#arrow");
var arrowRects = arrow.getBoundingClientRect();
var arrowX = arrowRects.left + arrowRects.width / 2;
var arrowY = arrowRects.top + arrowRects.height / 2;

addEventListener("mousemove", function(event) {
arrow.style.transform = "rotate(" + Math.atan2(event.y - arrowY, event.x - arrowX) + "rad)";
});
</script>

最佳答案

您可以通过监听 mousemove 事件来获取光标的位置。然后,使用旋转变换使箭头旋转。

function getCenter(element) {
const {left, top, width, height} = element.getBoundingClientRect();
return {x: left + width / 2, y: top + height / 2}
}

const arrow = document.querySelector("#arrow");
const arrowCenter = getCenter(arrow);
addEventListener("mousemove", ({clientX, clientY}) => {
const angle = Math.atan2(clientY - arrowCenter.y, clientX - arrowCenter.x);
arrow.style.transform = `rotate(${angle}rad)`;
});
html  {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
<div id="arrow">&gt;</div>

关于jquery - 将 div 旋转到鼠标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37261051/

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