gpt4 book ai didi

javascript - 如何用javascript通过点击来改变背景颜色?

转载 作者:行者123 更新时间:2023-12-02 14:12:43 26 4
gpt4 key购买 nike

我是编程新手,这是我第一次尝试学习新东西。我无法弄清楚我的代码有什么问题,因为它不想工作。我所需要的只是通过单击 div 来更改背景颜色。如果您删除第一行代码直到“功能”,但仅在加载页面时,它就会起作用。

document.getElementById("trying").onclick = function(){
var someText = document.getElementById("textArea").value;
document.getElementById("randomText").innerHTML = someText;
}
document.getElementById("mainBox").onclick =
function getRandomColor() {

var letters = '0123456789ABCDEF'.split('');

var color = '#';

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

color += letters[Math.floor(Math.random() * 16)];

}

return color;

}
document.getElementById("mainBox").style.backgroundColor = getRandomColor();
.mainBox {
width: 400px;
height:350px;
background-color:pink;
margin-right:auto;
margin-left:auto;
}
#textArea {
margin-left:100px;
}
<div id="mainBox" class="mainBox">
<p id="randomText" align="center">U know who you are?</p>
<input type="text" id="textArea">
<button id="trying">Try it!</button>
</div>

最佳答案

您设置 onClick 处理程序的方式是错误的。

document.getElementById("trying").onclick = function(){
var someText = document.getElementById("textArea").value;
document.getElementById("randomText").innerHTML = someText;
}

function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';

for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}

return color;
}

document.getElementById("mainBox").onclick = function() {
document.getElementById("mainBox").style.backgroundColor = getRandomColor();
}
.mainBox {
width: 400px;
height:350px;
background-color:pink;
margin-right:auto;
margin-left:auto;
}
#textArea {
margin-left:100px;
}
<div id="mainBox" class="mainBox">
<p id="randomText" align="center">U know who you are?</p>
<input type="text" id="textArea">
<button id="trying">Try it!</button>
</div>

关于javascript - 如何用javascript通过点击来改变背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39378443/

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