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

JavaScript - Math.floor(Math.random()) - Reposition <img> element

本文关键字:Math img 定位 元素 新定位 floor random -重 JavaScript      更新时间:2023-09-26

我正在尝试开发一个功能,随机重新定位一个元素在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>

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

 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>

删除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';
 }
var Hero = document.getElementById("image");
var x = Math.floor(Math.random() * 300);
Hero.style.left = x +'px';

它是这样工作的:

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

您必须将变量赋值给新的对象。

添加到你的代码中。

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

>