0

I have a function to follow the object after the mouse, and I want to be able to stop and start following at will, without hiding the object.

It almost works as I wanted, and is following the mouse indeed, but I cannot make it move initial position without actually moving the mouse.

E.G. When I trigger the function, the object is still somewhere in another place, until I move the mouse, but what I'm trying to do is to move it the initial position first, before attaching the mousemove event.

Here is how I want to trigger the function:

showtrail();

function showtrail(shit){
//this is how I tried to set the initial position first, but this get me an error:..
//followmouse(); 
document.onmousemove=followmouse; //and this is how I attach the event.
}

This is a part of the actual function to move the object, but, I can't get the coordinates if I try to initilize/imitate the first movement.

    function followmouse(e){
var xcoord=offsetfrommouse[0]
var ycoord=offsetfrommouse[1]
if (typeof e != "undefined"){  //This- if triggered by mousemove, and it works
xcoord+=e.pageX
ycoord+=e.pageY
}
else {   //this was meant for the initial call, but... for some reason
xcoord+=document.body.scrollLeft+event.clientX // it triggers an error,
ycoord+=document.body.scrollTop+event.clientY // saying event.clientX undefined.
}
}

So the event.clientX never seems to work, and I cannot figure out how to get the actual mouse position otherwise..

Please guide..

4

3 回答 3

0

event.clientX 和 event.clientY 是错误的。它们应该是 e.clientX 和 e.clientY

在 followmouse(e) 中获取 xcoord 和 ycoord 的更优雅的跨浏览器方法是:

xcoord = e.pageX||(e.clientX+(document.body.scrollLeft||document.documentElement.scrollLeft));
ycoord = e.pageY||(e.clientY+(document.body.scrollTop||document.documentElement.scrollTop));

现在,如果我做对了,后面的对象应该有一个初始的绝对位置并显示为一个块,这意味着你有初始的 x 和 y(左和上)。因此,通过使用全局 bool var 来判断当前是否跟随,你就完成了。

<style>
...
#trail {position:absolute;left:0;top:0;display:none}
...
</style>

<script>
var following = false;
...
function followmouse(e){
   if (!following){
       document.getElementById('trail').style.display='none';
       return;
   }
   ...
   document.getElementById('trail').style.display='block';
}
</script>

通过更改显示,您可以选择将#trail 移动到其初始位置然后跟随鼠标,以及避免移动并让它从最新的跟随位置跟随鼠标的选项。

于 2012-06-14T07:38:47.267 回答
0

编辑1:

为此,我建议使用requestAnimationFrameAPI,而不是经典的 DOM 事件。说API对于创建动画和暂停它们更有效。

也看看这个:requestAnimationFrame for smart animating


这很可悲,但在网页上移动鼠标之前您无法获得鼠标的初始位置。我的意思是你不能在mousemove事件发生之前校准你的对象。这就是我将在类似项目中做的事情:

<!DOCTYPE html>
<html>
    <head>
        <title>Title</title>
        <script type="text/javascript">
            var targetID = 'mydiv'; // div that is to follow the mouse
            var pauseFollowing = false;
            // (must be position:absolute)
            var offX = 15;          // X offset from mouse position
            var offY = 15;          // Y offset from mouse position

            function mouseX(evt) {if (!evt) evt = window.event; if (evt.pageX) return evt.pageX; else if (evt.clientX)return evt.clientX + (document.documentElement.scrollLeft ?  document.documentElement.scrollLeft : document.body.scrollLeft); else return 0;}
            function mouseY(evt) {if (!evt) evt = window.event; if (evt.pageY) return evt.pageY; else if (evt.clientY)return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); else return 0;}

            function follow(evt) {
                if(pauseFollowing) {
                    //or do something else at pause
                    return false;
                }
                var obj = document.getElementById(targetID).style;
                obj.visibility = 'visible';
                obj.left = (parseInt(mouseX(evt))+offX) + 'px';
                obj.top = (parseInt(mouseY(evt))+offY) + 'px';
            }

            function toggleFollow() {
                pauseFollowing = !pauseFollowing;
            }

            window.onload = function() {
                window.onclick = toggleFollow;
                document.onmousemove = follow;
            }
        </script>
    </head>
    <body>
        <div id="mydiv" style="visibility: hidden; top:0; left:0 ;width: 100px; height: 100px; background: #ff0; position: absolute;"></div>
    </body>
</html>
于 2012-06-14T07:56:02.483 回答
0

好吧,我就是这样做的。最好的想法是始终捕捉在全局变量中设置位置的动作。现在我可以选择将其固定在任何特定位置(如果我将坐标传递给 showtrail)或实际跟随鼠标;我还添加了一个事件侦听器,因此如果鼠标在跟随时移出窗口,它将被隐藏。到目前为止,它完全按照我的意愿工作:

var trailimage=["scripts/loading_mouse.gif", 24, 24] //image path, plus width and height
var offsetfrommouse=[2,10] //image x,y offsets from cursor position in pixels. Enter 0,0 for no offset
var global_coord=[0,0]
var follow=false;

if (document.getElementById || document.all)
document.write('<div id="trailimageid" style="z-index: 10;position:absolute;display:none;left:0px;top:0px;width:1px;height:1px"><img src="'+trailimage[0]+'" border="0" width="'+trailimage[1]+'px" height="'+trailimage[2]+'px"></div>')

function gettrailobj(){
if (document.getElementById)
return document.getElementById("trailimageid").style
else if (document.all)
return document.all.trailimagid.style
}

function hidett(){  gettrailobj().display="none";   }
function showtt(){  gettrailobj().display="block";  }

function truebody(){    return (document.body||document.documentElement);   }

function showtrail(shit){
    if (typeof shit == "undefined"){    //Follow Mouse
        follow=true;
        setmousepos(global_coord[0],global_coord[1]);
    }
    else {              //Set fixed in specific place
        follow=false;
        showtt()
        gettrailobj().left=shit.left+6+"px"
        gettrailobj().top=shit.top-5+"px"
    }
}

function hidetrail(){
    hidett()
    follow=false;
}

function setcoord(e){
var xcoord=offsetfrommouse[0]
var ycoord=offsetfrommouse[1]
var xxcoord = e.pageX||(e.clientX+truebody().scrollLeft);
var yycoord = e.pageY||(e.clientY+truebody().scrollTop);
if (typeof xxcoord != "undefined"&&typeof yycoord != "undefined"){
    xcoord+=xxcoord;
    ycoord+=yycoord;
    global_coord=[xcoord,ycoord];
    if (follow) setmousepos(xcoord,ycoord);
}}

function setmousepos(xcoord,ycoord){
    var docwidth=truebody().scrollLeft+truebody().clientWidth   
    var docheight=Math.max(truebody().scrollHeight, truebody().clientHeight)
    if ((xcoord+trailimage[1]+3>docwidth || ycoord+trailimage[2]> docheight ||!follow)){
        hidett()
    }
    else{
        showtt();
        gettrailobj().left=xcoord+"px"
        gettrailobj().top=ycoord+"px"
    }
}

window.addEventListener("mouseout",
    function(e){
        mouseX = e.pageX;
        mouseY = e.pageY;
        if ((mouseY >= 0 && mouseY <= window.innerHeight)
        && (mouseX >= 0 && mouseX <= window.innerWidth)){
            return false;
        }else{
            if (follow) hidett()
        }
    },
    false);

document.onmousemove=setcoord;
于 2012-06-14T19:04:40.793 回答