我想让div旋转到鼠标所在的位置,
因此,当我的鼠标离开时,必须显示<-
当我的鼠标位于右侧时必须显示->
这需要朝任何方向发展!
有没有人有解决方案?
编辑:
<style>
body {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
</style>
<div id="arrow">></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>
答案 0 :(得分:1)
您可以侦听鼠标移动事件以获取光标的位置。然后,使用旋转变换使箭头旋转。
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.clientY - arrowY, event.clientX - arrowX) + "rad)";
});
body {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
<div id="arrow">></div>
答案 1 :(得分:0)
metamask答案的jQuery版本。
var arrow = $('#arrow');
var arrowX = arrow.offset().left + arrow.outerWidth(true) / 2;
var arrowY = arrow.offset().top + arrow.outerHeight(true) / 2;
$(document).on('mousemove', function(event) {
var rad = Math.atan2(event.pageY - arrowY, event.pageX - arrowX);
arrow.css('transform', 'rotate('+rad+ 'rad)');
});
body {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="arrow">></div>