简体   繁体   English

HTML / JavaScript的新手,如何使用onclick更改JavaScript的背景颜色

[英]Very new to HTML/JavaScript, how do I use onclick to change background color with JavaScript

When the page loads I want the page to be black and when you click it should change to white. 页面加载时,我希望页面为黑色,单击时应更改为白色。 I have the Javascript code to change it to white but I'm not sure how to change it to white only when you click. 我有将其更改为白色的Javascript代码,但我不确定仅在单击时如何将其更改为白色。

#divMain {
position:absolute;
left:0px;
top:0px;
width:320px;
height:460px;
background-color:black;

Here I need to change background-color to white on click. 在这里,我需要单击将背景色更改为白色。

function body_load() {
document.getElementById('divMain').style.backgroundColor = "rgb(255,255,255)";}

Here is the Javascript function I use to change the background to white. 这是我用来将背景更改为白色的Javascript函数。 How can I only have it change to white when I click? 单击时如何只将其更改为白色?

Also, when the page loads the function body_load() is ran. 同样,当页面加载时,函数body_load()也将运行。

well add to the body tag: 并添加到body标签:

<body onclick="body_load()">

if you want only divMain clickable: 如果只希望divMain可点击:

var body_load = function() {
    document.getElementById('divMain').style.backgroundColor = "rgb(255,255,255)";
}
window.onload = function(){
    document.getElementById('divMain').onclick = body_onload;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM