根据计算的RNG动态调整分区/元素的大小

Resize Div/Element dynamically based on calculated RNG

本文关键字:元素 分区 动态 计算 RNG 调整      更新时间:2023-09-26

所以我试图创建一个脚本,让我点击页面上的一个按钮,然后链接到它的JS函数将生成一个1-1000之间的随机数,并被设置为div的维度。Chrome检查器显示属性正在发生变化,但页面上的内容本身没有变化。

<button onclick="myFunction()">Try it</button>
<div id="block" style="background-color:blue;">
</div>
function myFunction() {
    document.getElementById("block").setAttribute("width", Math.floor(Math.random() * 1001) + "px" );
document.getElementById("block").setAttribute("height", Math.floor(Math.random() * 1001) + "px" );
}

jsfiddle:http://jsfiddle.net/NR2k6/118/

您想要设置元素的style,而不是属性:

var d = document.getElementById("block");
d.style.width = Math.floor(Math.random() * 1001) + "px" ;
d.style.height= Math.floor(Math.random() * 1001) + "px" ;