我正在学习JavaScript,作为练习,我制作了一个简单版本的画图应用(没有使用Canvas)。这个项目非常简单。我创建了一个div作为画笔,当我开始绘图时,新的div会被创建。不幸的是,更改画笔颜色的按钮(div的颜色)不起作用。我非常想知道我犯了什么错误 :)
以下是我的代码:
以下是我的代码:
let clicked = false;
const dane = function(e) {
if (clicked == false) return;
var x = e.clientX;
var y = e.clientY;
var div = document.createElement("div");
div.style.top = y + "px";
div.style.left = x + "px";
document.body.appendChild(div);
}
const klik = function(e) {
var x = e.clientX;
var y = e.clientY;
var div = document.createElement("div");
div.style.top = y + "px";
div.style.left = x + "px";
document.body.appendChild(div);
}
const tak = function() {
clicked = true;
}
const nie = function() {
clicked = false;
}
function paint() {
document.body.addEventListener("mousemove", dane);
document.body.addEventListener("mousedown", tak);
document.body.addEventListener("mouseup", nie);
document.body.addEventListener("click", klik);
}
// change color below
let color = document.getElementsByTagName("div");
color.blue = function() {
this.style.backgroundColor = "blue";
}
color.red = function() {
this.style.backgroundColor = "red";
}
color.green = function() {
this.style.backgroundColor = "green";
}
window.onload = paint;
body {
background-color: black;
height: 100vh;
margin: 0;
color: white;
}
div {
width: 10px;
height: 10px;
border-radius: 50%;
background-color: white;
position: absolute;
}
#btnblue {
position: fixed;
margin-top: 25px;
margin-left: 25px;
width: 100px;
height: 100px;
background-color: aqua;
z-index: 100;
}
#btnred {
position: fixed;
margin-top: 150px;
margin-left: 25px;
width: 100px;
height: 100px;
background-color: red;
z-index: 100;
}
#btngreen {
position: fixed;
margin-top: 275px;
margin-left: 25px;
width: 100px;
height: 100px;
background-color: chartreuse;
z-index: 100;
}
<button id="btnblue" onclick="blue();"></button>
<button id="btnred" onclick="red();"></button>
<button id="btngreen" onclick="green();"></button>
color.blue = function() { this.style.backgroundColor = "blue"; }
这段代码的作用是什么?它是在 HTML 集合中添加了一个blue
属性,但从未调用过。 - connexo