<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Etch-A-Sketch</title>
</head>
<body>
<h1>Etch-A-Sketch</h1>
<p id="Grid-Size">Grid Size</p>
<form onsubmit="getTotalGridSize()"> <!--onsubmit has to be on the form tag not the submit input-->
<input type="number" placeholder="size" min="1" max="100" id ="size" value="" oninput="getSizeValue()">
<input type="submit" id="Submit" value="Submit" onclick="createTile()">
</form>
<p id="Colors">Choose Color</p>
<form id="color-options" >
<input type="radio" name="choice" value="blue">
<label for="default">Default</label>
<input type="radio" name="choice" value="random" >
<label for="random">Random</label>
<input type="radio" name="choice" value="white" >
<label for="white">White</label>
<input type="radio" name="choice" value="user" >
<label for="color-picker">Color Picker</label>
<input type="color" id="color-picker" value="">
</form>
<div id="Sketch">
<div id="tile" onmouseover="updateHoverColor()">
</div>
</div>
<script src="etch.js" charset="utf-8"></script>
</body>
</html>
//Dom Accessed Variables
let tile = document.getElementById("tile")
let sizeValue = null
let gridSize= null
let containerDiv = document.getElementById("sketch")
//input functions
function getSizeValue() {
sizeValue = document.getElementById('size').value //getting the inputs value
}
function getTotalGridSize() {
gridSize = sizeValue * sizeValue
}
//Generates random RGB values
function randomColor() {
let red = Math.floor(Math.random() * 255 + 1);
let blue = Math.floor(Math.random() * 255 + 1);
let green = Math.floor(Math.random() * 255 + 1);
//Returns string with style to be applied
let random = `rgb(${red}, ${green}, ${blue})`;
tile.style.backgroundColor = random;
}
function updateHoverColor() {
let colorChoice = document.getElementById("color-picker").value
if(document.querySelector('#color-options > input:checked').value === "blue") {
tile.style.backgroundColor = "blue"
} else if (document.querySelector('#color-options > input:checked').value === "random") {
randomColor()
} else if (document.querySelector('#color-options > input:checked').value === "white") {
tile.style.backgroundColor = "white"
} else if (document.querySelector('#color-options > input:checked').value === "user") {
tile.style.backgroundColor = colorChoice;
}
}
function createTile() {
let baby = document.createElement("div");
baby.style.height = "200px"
baby.style.width = "100px"
baby.style.backgroundColor = "black"
document.body.appendChild(baby)
}
因此,我想做的是在用户单击“提交”按钮后在其容器div中创建另一个div。我使用JavaScript创建了一个函数,然后将其附加到同一按钮的onclick上。我什至遵循完全相同的语法从W3schools创建函数以创建,追加和添加元素,但是它似乎在我的代码中根本不起作用,并且我试图找出原因。
function myFunction() {
//code
}