使图像随机移动,点击

Make image randomly move onclick

本文关键字:点击 移动 随机 图像      更新时间:2023-09-26

我正在尝试使用纯javascript随机移动图像。点击事件后,图像位置应根据生成的随机数移动。

下面是我的代码:
<html>
<head><title> Move Image </title>
<style type="text/css">
#smiley { position: relative; top: 0px; left: 0px; }
</style>
<script type="text/javascript">
function changeImg()
{
var x = Math.floor(Math.random()*300);
var y = Math.floor(Math.random()*300);

var obj = document.getElementById("emotion");
obj.style.top = x + "px";
obj.style.left = y + "px";

 obj.onclick= "changeImg();"
 }
</script>
</head>
<body>
<img id="emotion" 
src="http://www.google.com/images/srpr/logo4w.png" 
width="42" height="42">
</body>
</html>

任何想法?谢谢你!

在所有浏览器中不需要内联脚本

Codepen demo

var object = document.getElementById('item');
object.onclick=function(){
    var x = Math.floor(Math.random()*300);
    var y = Math.floor(Math.random()*300);
    object.style.top = x + 'px';
    object.style.left = y + 'px';
};
HTML

<img id="item" src="http://...png" />
CSS

#item { 
  cursor: pointer;
  position: absolute; 
  top: 0px; 
  left: 0px; 
  transition: all 1s;
}
  • 您从未将changeImg()分配给<img>

    <img ... onclick="changeImg()">
    
  • 如果您计划使用topleft,元素必须是position: absolute

  • <img>标签的ID是emotion,不是smiley

  • 您不需要在每次调用changeImg()函数时设置<img>onclick属性。一次就够了。

您从未设置图像对象的位置。相反,你将"smiley"设置为相对的,但图像是"emotion"。

#emotion{ position: relative; top: 0px; left: 0px; }

我建议你调用函数而不是字符串字面值。例子:

obj.onclick = changeImg;
<html>
<head><title> Move Image </title>
<style type="text/css">
#emotion { position: absolute; top: 0px; left: 0px; border:1px solid red;}
</style>
<script type="text/javascript">
function changeImg()
{
var x = Math.floor(Math.random()*300);
var y = Math.floor(Math.random()*300);

var obj = document.getElementById("emotion");
obj.style.top = x + "px";
obj.style.left = y + "px";

 }
</script>
</head>
<body>
<img id="emotion" 
src="http://www.google.com/images/srpr/logo4w.png" 
width="150" height="42" onclick="changeImg()"/>
</body>
</html>