【问题标题】:JavaScript - Math.floor(Math.random()) - Reposition <img> elementJavaScript - Math.floor(Math.random()) - 重新定位 <img> 元素
【发布时间】:2016-11-04 12:32:33
【问题描述】:
我正在尝试开发一个在 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
【解决方案1】:
我建议只使用元素本身,因为你有一个原始值(字符串)作为引用,而不是对样式的引用。
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>
【解决方案2】:
移除 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';
}
【解决方案3】:
var Hero = document.getElementById("image");
var x = Math.floor(Math.random() * 300);
Hero.style.left = x +'px';
【解决方案4】:
它是这样工作的:
var Hero = document.getElementById("image");
var x = Math.floor(Math.random() * 300);
Hero.style.left = x +'px';
【解决方案5】:
您必须将变量分配给新对象。
将此添加到您的代码中。
Hero.style.left = HeroY;
Hero.style.left = HeroX;
无论如何,img 只是在 Y 轴上移动。