我正在使用document.getElementById(“”)。style.top = var;每次点击它时随机改变一个物体的位置,但我只能按像素而不是百分比随机改变位置。如何使用%?
随机生成数字document.getElementById("randObject").onclick = function () {
var bColor = "#"+((1<<24)*Math.random()|0).toString(16);
var yAxis = Math.random()*100;
var xAxis = Math.random()*100;
document.getElementById("randObject").style.backgroundColor = bColor;
document.getElementById("randObject").style.top = yAxis;
document.getElementById("randObject").style.left = xAxis;
}
答案 0 :(得分:1)
document.getElementById("randObject").style.top = yAxis + "%";
document.getElementById("randObject").style.left = xAxis + "%";
我应该指出你的颜色发生器在1/16的时间内也无效。你需要左键填充字符串:
"#" + ("00000" + ((1<<24) * Math.random() | 0).toString(16)).slice(-6);
可用于保存DOM查找时间的另一种快捷方式是在点击事件中使用this
关键字。它们一起看起来像:
最后,您可能会考虑使用.addEventListener('click', function() { ... })
,因为这是当前的标准,但如果您真的想要支持IE6,那么您正在做的工作正常。
让我们看看演示,因为现在它看起来像一个非常简洁的脚本:
document.getElementById("randObject").addEventListener('click', function() {
var bColor = "#" + ("00000" + ((1<<24) * Math.random() | 0).toString(16)).slice(-6);
var yAxis = Math.random() * 100;
var xAxis = Math.random() * 100;
this.style.backgroundColor = bColor;
this.style.top = yAxis + "%";
this.style.left = xAxis + "%";
});
:root {
/* change this value to update the size of playing field and #randObject */
--size: 50px;
}
html {
position: absolute;
margin: 0 var(--size) var(--size) 0;
padding: 0;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
body {
margin: 0;
padding: 0;
}
#randObject {
position: absolute;
top: 0;
left: 0;
width: var(--size);
height: var(--size);
background-color: #000000;
border-radius: 50%;
cursor: pointer;
transition-property: top, left, background-color;
transition-duration: 0.4s;
}
<div id="randObject"></div>
答案 1 :(得分:0)
我为你的代码添加了定位,我能够按百分比移动它。
<img id="randObject" width=100 height=100>
<script>
document.getElementById("randObject").onclick = function () {
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var bColor = "#"+((1<<24)*Math.random()|0).toString(16);
var yAxis = Math.random() + '%';
var xAxis = Math.random() + '%';
document.getElementById("randObject").style.backgroundColor = bColor;
document.getElementById("randObject").style.top = yAxis;
document.getElementById("randObject").style.left = xAxis;
document.getElementById("randObject").style.position = 'absolute';
}
</script>