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

标签 javascript

我是编程新手,这是我第一次尝试学习新东西。我无法弄清楚我的代码有什么问题,因为它不想工作。我所需要的只是通过单击 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/

相关文章:

javascript - 无法执行操作的 php 按钮

javascript - 什么正则表达式匹配 JavaScript 中字符串中的双引号字符串?

javascript - XUL(特别是 Firefox)状态栏定位如何工作?

javascript - 火力地堡 : Convert promise to async/await

javascript - 如何伪造图片的加载 gif

javascript - Mongodb:如何从数据库中获取第一个文档然后将其删除

javascript - html - 选择范围 - 获取范围+起始节点+结束节点+距离

php - 表单提交单选

javascript - 通过嵌套的对象数组递归循环以编写嵌套列表

Javascript,添加构造函数的类