我试图通过单击一个按钮来创建Divs,但它只是用红色填充了按钮范围。
<div class="app">
<button onclick="createDiv()">Make a cube</button>
</div>
<script>
function createDiv ()
{
var boxEle = document.querySelector('.app');
boxEle.style.width = 100;
boxEle.style.height = 100;
boxEle.style.backgroundColor = '#f00';
}
</script>
首先,在函数中,您正在html中选择一个已经创建的div,因此您没有在创建div。如果要使用javascript创建div,可以这样做。
function createDiv() {
let box = document.createElement('div'); // creates div
box.classlist.add('box-styling') // you can add a class and style it using that instead
let container = document.querySelector('.container') // div has to be placed somewhere in html, so create a container and select it.
container.appendChild(box) // then append to container
}
这应该做:
<div class="app">
<button onclick="createDiv()">Make a cube</button>
</div>
<script>
function createDiv () {
var boxEle = document.querySelector('.app');
var newDiv = document.createElement('div');
newDiv.style.width = 100;
newDiv.style.height = 100;
newDiv.style.margin = 5;
newDiv.style.backgroundColor = '#f00';
boxEle.appendChild(newDiv);
}
</script>