如何将图像移动到 html/javascript 中的鼠标位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6508139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:54:20  来源:igfitidea点击:

How to move an image to the mouse position in html/javascript?

javascripthtml

提问by Klaim

I'm getting slowly back to javascript and I'm a bit lost on basics. I just want to move an image to follow the mouse position. Here is a simple code I've been tweaking for some time without any success :

我正在慢慢地回到 javascript 并且我有点迷失在基础知识上。我只想移动图像以跟随鼠标位置。这是我已经调整了一段时间但没有任何成功的简单代码:

<html>
<head>

</head>
<body>

<img id="avatar" src="Klaim.png" style="position:absolute;" />
</body>

<script lang="javascript">

function updateAvatarPosition( e )
{
    var avatar = document.getElementById("avatar");
    avatar.x = e.x;
    avatar.y = e.y;

    // alert( "e( " + e.x + ", " + e.y + " )" );    
    // alert( "avatar( " + avatar.x + ", " + avatar.y + " )" );
}

document.onmousemove = updateAvatarPosition;


</script>

</html>

It looks a lot like some tutorials to do this very thing. What I don't understand is that using the alerts (I don't know how to print in the browser's javascript console) I see that avatar.x and y are never changed. Is it related to the way I've declared the image?

它看起来很像一些教程来做这件事。我不明白的是,使用警报(我不知道如何在浏览器的 javascript 控制台中打印)我看到 avatar.x 和 y 永远不会改变。它与我声明图像的方式有关吗?

Can someone point me what I'm doing wrong?

有人可以指出我做错了什么吗?

回答by Sascha Galley

I think that you don't want to set xand y, but rather style.leftand style.top!

我认为您不想设置xand y,而是设置style.leftand style.top

avatar.style.left = e.x;
avatar.style.top = e.y;

回答by chrisf

There is no xand yproperty for avatar - you should use 'top'and 'left'instead. Also, move the var avatar = document.getElementById("avatar");declaration outside of the function, as you only need to do this once.

avatar没有xandy属性 - 您应该使用'top'and'left'代替。此外,将var avatar = document.getElementById("avatar");声明移到函数之外,因为您只需要执行一次。

回答by Kev

<html>
<head>

</head>
<body>

<img id="avatar" src="Klaim.png" style="position:absolute;" />
</body>

<script lang="javascript">

function updateAvatarPosition( e )
{
    var avatar = document.getElementById("avatar");
    avatar.style.left = e.x + "px";
    avatar.style.top = e.y + "px";

    //alert( "e( " + e.x + ", " + e.y + " )" );    
    //alert( "avatar( " + avatar.x + ", " + avatar.y + " )" );
}

document.onmousemove = updateAvatarPosition;


</script>

</html>

回答by MooGoo

avatar.style.top = e.clientY + 'px';
avatar.style.left = e.clientX + 'px';