5

I am attempting to make a image move randomly using plain javascript. Upon the event onclick the image location should move according to the random number that is generated.

Here is my code:

<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>

Any idea? Thank you!

4

4 回答 4

2

这个在所有浏览器中都可以在没有内联脚本的情况下工作

Codepen 演示

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;
}
于 2015-06-20T13:41:07.753 回答
1
  • 你永远不会分配changeImg()<img>

    <img ... onclick="changeImg()">
    
  • position: absolute如果您打算使用topand ,则该元素必须是left

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

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

于 2013-03-19T21:39:40.780 回答
0

您永远不会设置图像对象的位置。相反,您将“笑脸”设置为相对,但图像是“情感”。

尝试

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

我建议您调用函数而不是字符串文字。例子:

obj.onclick = changeImg;
于 2013-03-19T21:42:13.440 回答
-1
<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>
于 2016-09-25T21:26:09.673 回答