JavaScript - Math.floor(Math.random()) -重新定位<img>元素
JavaScript - Math.floor(Math.random()) - Reposition <img> element
我正在尝试开发一个功能,随机重新定位一个元素在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;
>相关文章:
- 如何更改<svg>标记为<img>用js标记
- 有没有一种方法可以防止img get请求使用css或js发生
- Javascript:使用绝对路径设置img src
- Setting default onclick behavior for <img> tag in gene
- 如何在页面加载中使用Jquery/Javascript确定img源
- 图像可以从源<img src=""/>.TEXT可以在没有javascript的情况下从外部
- 如何防止Math.max()返回NaN
- 使用AngularJs时,如何在img标记具有src-attr时设置数据src
- 插入“;img src"在javascript中
- 检索MongoDB binData并显示为<img>src
- Math.min()和Math.max()之间有什么区别?在Javascript中
- addEventListener的Javascript代码不工作!?(单击时打开放大的img)
- 手柄'img'单击事件并插入'alt'使用jQuery将属性转换为文本框
- 限制对HTML/CSS/IMG或根索引文件夹的访问
- 使用javascript或angularjs特定过滤器搜索字符串中第一个img标记的json值
- JavaScript Vector2d Math
- 为img设置高度和宽度
- 替换与单词'匹配的文本字符;购物车'替换为img图标
- Math.exp() for bigInt?
- 我应该如何在 UL 内触发 IMG 标签的点击