gpt4 book ai didi

javascript - JS 中的混​​色器不起作用

转载 作者:行者123 更新时间:2023-11-28 00:20:53 25 4
gpt4 key购买 nike

我正在尝试创建一个颜色混合器,当您单击前两个 div 时,它们会改变颜色。前两个 div 的颜色组合应该使第三个 div 成为前两个 div 的混合。因此,如果前两个 div 是红色的,那么第三个 div 也应该是红色的。它不起作用,控制台显示 Uncaught TypeError:无法读取未定义的属性“backgroundColor”。

HTML

    <!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>

div {
width: 100px;
height: 100px;
background-color: #00DD00;
margin: 5px;
float: left;
}

</style>
</head>
<body>
<script src="js/main.js"></script>
</body>
</html>

这是我的 JS

for(var i = 0; i < 1; i++) {

var newDiv = document.createElement("div");
newDiv.addEventListener('click', changeColor);
document.body.appendChild(newDiv);

var newDivTwo = document.createElement("div");
newDivTwo.addEventListener('click', changeColor);
document.body.appendChild(newDivTwo);

var newDivThree = document.createElement("div");
newDivThree.addEventListener('click', changeColor);
document.body.appendChild(newDivThree);

}

function changeColor(newDiv, newDivTwo, newDivThree){
if (newDiv.style.backgroundColor =='rgb(255, 0, 0)' && newDivTwo.style.backgroundColor =='rgb(255, 0, 0)'){
newDivThree.style.backgroundColor ='rgb(255, 0, 0)';
}
else if (newDiv.style.backgroundColor =='rgb(255, 0, 0)' && newDivTwo.style.backgroundColor=='rgb(0, 0, 255)'){
newDivThree.style.backgroundColor='rgb(255, 0, 255)';
}

}

最佳答案

首先,您不需要一个循环来只执行一次迭代。其次,该函数期望在参数列表中发送值,但它们永远不会被发送。因此,它将这些视为 null,然后您尝试引用 null 的属性,这就是您收到该错误的原因。

var newDiv = document.createElement("div");
newDiv.addEventListener('click', changeColor);
document.body.appendChild(newDiv);

var newDivTwo = document.createElement("div");
newDivTwo.addEventListener('click', changeColor);
document.body.appendChild(newDivTwo);

var newDivThree = document.createElement("div");
newDivThree.addEventListener('click', changeColor);
document.body.appendChild(newDivThree);

function changeColor(){
if (newDiv.style.backgroundColor =='rgb(255, 0, 0)' && newDivTwo.style.backgroundColor =='rgb(255, 0, 0)'){
newDivThree.style.backgroundColor ='rgb(255, 0, 0)';
}
else if (newDiv.style.backgroundColor =='rgb(255, 0, 0)' && newDivTwo.style.backgroundColor=='rgb(0, 0, 255)'){
newDivThree.style.backgroundColor='rgb(255, 0, 255)';
}

}

您现在应该能够处理颜色更改逻辑

关于javascript - JS 中的混​​色器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30035926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com