我正在尝试使用普通 javascript 使图像随机 move 。 发生 onclick 事件时,图像位置应根据生成的随机数 move 。
这是我的代码:
<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>
有什么想法吗? 谢谢!
最佳答案
这个在所有浏览器中都不需要内联脚本
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;
}
关于javascript - 使图像随机 move onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15510922/