JavaScript - Math.floor(Math.random()) - 重新定位元素

问题描述 投票:1回答:5

我正在尝试开发一个随机重新定位Web文档元素的函数。我当前的JavaScript程序不会随机更改元素id =“image”的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>
javascript html random styles
5个回答
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
投票

删除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';
 }

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

0
投票

它的工作原理如下:

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

0
投票

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

将此添加到您的代码中。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.