JavaScript - Math.floor(Math.random()) - 重新定位<img/>元素

时间:2016-11-04 12:32:34

标签: javascript html random styles

我正在尝试开发一个随机重新定位Web文档元素的函数。我当前的JavaScript程序不会随机更改元素id =&#34; image&#34;的element.style.left和element.style.top值。谢谢你的帮助!

<html> <body>

<img id="image" src="happy.jpg" style="position:absolute;left:0px; 
top:0px; width:50px; height:50px;" />

<button onclick="RandomPositions()"> Random Position </button>

<script>
 function RandomPositions() {
    var Hero = document.getElementById("image");
    var x = Math.floor(Math.random() * 300);
    var HeroX = Hero.style.left;
    HeroX = x + 'px';
    var y = Math.floor(Math.random() * 300);
    var HeroY = Hero.style.top; 
    HeroY = y + 'px';
 }
</script>
</body>
</html>

5 个答案:

答案 0 :(得分:2)

我建议只使用元素本身,因为你有一个原始值(字符串),而不是对样式的引用。

 function RandomPositions() {
    var Hero = document.getElementById("image");
    var x = Math.floor(Math.random() * 300);
    var y = Math.floor(Math.random() * 300);
    Hero.style.top = y + 'px';
    Hero.style.left = x + 'px';       
 }
<img id="image" src="http://lorempixel.com/75/75/" style="position:absolute;left:0px; 
top:0px; width:50px; height:50px;" />
<button onclick="RandomPositions()"> Random Position </button>

答案 1 :(得分:1)

删除HeroX和HeroY变量。更改这些变量时,图像样式不会改变。

function RandomPositions() {
    var Hero = document.getElementById("image");
    var x = Math.floor(Math.random() * 300);
    Hero.style.left = x + 'px';
    var y = Math.floor(Math.random() * 300);
    Hero.style.top = y + 'px';
 }

答案 2 :(得分:1)

var Hero = document.getElementById("image");
var x = Math.floor(Math.random() * 300);
Hero.style.left = x +'px';

答案 3 :(得分:0)

它的工作原理如下:

var Hero = document.getElementById("image");
var x = Math.floor(Math.random() * 300);
Hero.style.left = x +'px';

答案 4 :(得分:0)

您必须将变量分配给新对象。

将此添加到您的代码中。

Hero.style.left = HeroY;
Hero.style.left = HeroX;

无论如何,img正在Y轴上移动。