use*_*152 5 html javascript css image move
我正在尝试使用纯 JavaScript 使图像随机移动。onclick 事件发生后,图像位置应根据生成的随机数移动。
这是我的代码:
<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>
Run Code Online (Sandbox Code Playgroud)
任何想法?谢谢你!
你永远不会分配changeImg()给<img>
<img ... onclick="changeImg()">
Run Code Online (Sandbox Code Playgroud)position: absolute如果您计划使用topand ,则该元素必须是left。
该<img>标签的 ID 为emotion,而不是smiley。
您不需要在每次调用该函数时都设置<img>'s属性。一次就够了。onclickchangeImg()