更改鼠标跟随器以响应鼠标移动方向

时间:2015-06-30 00:58:28

标签: javascript mouseevent

我正在尝试让鼠标跟随者改变它的图像,这取决于它移动以赶上鼠标的方向(例如,一个小精灵精灵转向然后向前移动)。这是我到目前为止所做的,但它不起作用。 我做错了什么?(另外,我使用的是tumblr,因此它的语法与普通的javascrpit略有不同。)

var x=ox=400;
var y=oy=300;
foll=document.getElementById('follower');
document.onmousemove=function(e) {
    y=e.clientY;
    x=e.clientX;
    if (y!=oy || x!=ox) {
        foll.style.left=parseInt(foll.style.left)+(y-oy)+'px';
        foll.style.top=parseInt(foll.style.top)+(x-ox)+'px';
        var q=Math.ceil(((Math.atan((y-oy)/(x-ox)))*(180/Math.PI))/45);

这个讨厌的数学方程式(上图)应该得到鼠标的旧地方和新地方之间的角度,然后将它放在跟随者周围的八个方向上。

        if (q==1 || q==8) {foll.source = {image:Follower Right};} //RIGHT
        if (q==2 || q==3) {foll.source = {image:Follower Up};} //UP
        if (q==4 || q==5) {foll.source = {image:Follower Left};} //LEFT
        if (q==6 || q==7) {foll.source = {image:Follower Down};} //DOWN
        ox=x;
        oy=y;
    }
}

1 个答案:

答案 0 :(得分:0)

好的,这可能会关闭,但它有点工作。

我没有为每个游标设置图像源,而是根据方向传递了一个类,只是通过css更改了游标属性(这应该比使用图像源更快)。

所以代码看起来像这样:

var x=ox=400;
var y=oy=300;
foll=document.getElementById('follower');
document.onmousemove=function(e) {
    y=e.clientY;
    x=e.clientX;
    if (y!=oy || x!=ox) {
        foll.style.left=parseInt(foll.style.left)+(y-oy)+'px';
        foll.style.top=parseInt(foll.style.top)+(x-ox)+'px';
        var q=Math.ceil(((Math.atan((y-oy)/(x-ox)))*(180/Math.PI))/45);
        if (q==1 || q==8) {foll.className = 'cursorR'}; //RIGHT
        if (q==2 || q==3) {foll.className = 'cursorU'}; //UP
        if (q==4 || q==5) {foll.className = 'cursorL'}; //LEFT
        if (q==6 || q==7) {foll.className = 'cursorD'}; //DOWN
        ox=x;
        oy=y;
    }
}

然后是四个与你想要设置的光标对应的类:

.cursorR {
    cursor: e-resize;
}
.cursorU {
    cursor: n-resize;
}
.cursorL {
    cursor: w-resize;
}
.cursorD {
    cursor: s-resize;
}

我有updated the fiddle

似乎只有两个if语句被评估为true,所以你只能看到光标向右和向上光标。

您从哪里获得原始js代码?

对于光标参考,请参阅mdsn reference(如果您愿意,可以将自定义网址传递给图片)。