我遇到 getElementById() 无法正常工作的问题,我不确定出了什么问题。
我的 HTML 正文:
<button type="button" id="up">Increase Volume</button>
<button type="button" id="down">Decrease Volume</button>
<script src="final.js"></script>
我的脚本文件:
const upButton = document.getElementById("up");
const downButton = document.getElementById("up");
initialize();
function initialize(){
upButton.setAttribute("width", "300px");
console.log(upButton.getAttribute("width"));
upButton.setAttribute("left", (Math.floor(Math.random() * 1000)).toString() + "px");
downButton.setAttribute("top", (Math.floor(Math.random() * 1000)).toString() + "px");
downButton.setAttribute("left", (Math.floor(Math.random() * 1000)).toString() + "px");
}
您正在使用
setAttribute
并期望进行不同的操作。
当您执行
upButton.setAttribute("width", "300px");
时,您实际上是在执行以下操作:
<button type="button" class="button" id="up" width="600px" left="359px" style="width: 300px;">Increase Volume</button>
如果单击按钮上的“检查元素”,这是可见的。如果按钮实际上使用了这些属性,那么这将起作用。
参见文档:https://www.w3schools.com/jsref/met_element_setattribute.asp
现在要真正实现你想要的,正如另一条评论所建议的,你应该瞄准样式对象:
const upButton = document.getElementById("up");
const downButton = document.getElementById("down");
function initialize(){
upButton.style.width = '300px'
upButton.style.left = (Math.floor(Math.random() * 1000)).toString() + "px"
downButton.style.top = (Math.floor(Math.random() * 1000)).toString() + "px"
downButton.style.left = (Math.floor(Math.random() * 1000)).toString() + "px"
}
initialize();
.button {
position: absolute;
}
<button type="button" onclick="initialize()">Change position</button>
<button type="button" class="button" id="up">Increase Volume</button>
<button type="button" class="button" id="down">Decrease Volume</button>