如何将图像移动到 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
How to move an image to the mouse position in html/javascript?
提问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 x
and y
, but rather style.left
and style.top
!
我认为您不想设置x
and y
,而是设置style.left
and style.top
!
avatar.style.left = e.x;
avatar.style.top = e.y;
回答by chrisf
There is no x
and y
property 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没有x
andy
属性 - 您应该使用'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';