作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有跟随鼠标光标的图像。
HTML:
<img id="cow" src="https://icons.iconarchive.com/icons/gakuseisean/ivista-2/128/Alarm-Arrow-Right-icon.png" height="30px" width="30px" style="position: absolute; top: 50%; left: 50%;"/>
Javascript:
var mouseXY = {};
$( document ).on( "mousemove", function( event ) {
mouseXY.X = event.pageX;
mouseXY.Y = event.pageY;
});
var iCow = $("#cow");
var cowInterval = setInterval(function()
{
var cowXY = iCow.position();
var diffX = cowXY.left - mouseXY.X;
var diffY = cowXY.top - mouseXY.Y;
var newX = cowXY.left - diffX / 1000;
var newY = cowXY.top - diffY / 1000;
iCow.css({left: newX, top: newY});
}, 10);
如何让图片沿光标方向旋转?
我尝试用 transform: rotate()
:
var cowInterval = setInterval(function()
{
var cowXY = iCow.position();
var diffX = cowXY.left - mouseXY.X;
var diffY = cowXY.top - mouseXY.Y;
var newX = cowXY.left - diffX / 1000;
var newY = cowXY.top - diffY / 1000;
var tan = diffX / diffY;
var atan = Math.atan(tan);
iCow.css({left: newX, top: newY, transform: "rotate(" +((-1)*atan - Math.PI/2)+ "rad)"});
}, 10);
但没有成功
最佳答案
在更改光标位置时,您只需要更改 transform(rotate) css 属性,请记住,光标实际上改变了位置。
添加这两个if-else条件,使图片向正确的方向旋转
if(diffY > 0 && diffX > 0) {
atan += 180;
}
else if(diffY < 0 && diffX > 0) {
atan -= 180;
}
我想这就是你想要的。
var mouseXY = {};
$( document ).on( "mousemove", function( event ) {
mouseXY.X = event.pageX;
mouseXY.Y = event.pageY;
});
var iCow = $("#cow");
var prevXY = {X: null, Y: null};
var cowInterval = setInterval(function()
{
if(prevXY.Y != mouseXY.Y || prevXY.X != mouseXY.X && (prevXY.Y != null || prevXY.X != null)) {
var cowXY = iCow.position();
var diffX = cowXY.left - mouseXY.X;
var diffY = cowXY.top - mouseXY.Y;
var tan = diffY / diffX;
var atan = Math.atan(tan)* 180 / Math.PI;;
if(diffY > 0 && diffX > 0) {
atan += 180;
}
else if(diffY < 0 && diffX > 0) {
atan -= 180;
}
prevXY.X = mouseXY.X;
prevXY.Y = mouseXY.Y;
iCow.css({transform: "rotate(" + atan + "deg)"});
}
}, 10);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="cow" src="https://icons.iconarchive.com/icons/gakuseisean/ivista-2/128/Alarm-Arrow-Right-icon.png" height="30px" width="30px" style="position: absolute; top: 50%; left: 50%;"/>
关于javascript - 如何在 JavaScript 中旋转跟随光标的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39572125/
我是一名优秀的程序员,十分优秀!