使用Javascript更改网页的背景颜色 [英] Change Background Color of Webpage Using Javascript

查看:450
本文介绍了使用Javascript更改网页的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java语言的菜鸟,所以我在努力做到这一点.当用户单击这三个按钮之一时,我必须更改网页的背景颜色.这是我在HTML中的代码.

I am a noob to Javascript so I am struggling with how to do this. I have to change the background color of my webpage when the user clicks on one of these three buttons. This is my code in the HTML.

 <li id ="yellow" ></li>

 <li id="orange" ></li>

 <li id="red" ></li>

因此,当用户单击那些链接时,网页的背景颜色需要更改为该颜色.用javascript做到这一点的最佳方法是什么?

So when the user clicks on those links the background color of the webpage needs to change to that color. What is the best way to do this with javascript?

我尝试过

function changeBGC (color) {
document.bgColor= color;
}

并将我的html更改为此

and changed my html to this

 <li id ="yellow" onClick="changeBGC('yellow')" ></li>

 <li id="orange" onClick="changeBGC('orange')"></li>

 <li id="red" onClick="changeBGC('red')"></li>

点击链接后没有任何反应

Nothing happens when I click the links

推荐答案

您可以尝试以下操作( 示例 )

You may try this (Example)

HTML:

<ul id="colorSet">
    <li>Yellow</li>
    <li>Orange</li>
    <li>Red</li>
</ul>

JS:

window.onload = function(){
    var ul = document.getElementById('colorSet');
    ul.onclick = function(e){
        var evt = e || window.event;
        var target = evt.target || evt.srcElement;
        document.body.style.backgroundColor = target.innerHTML;
    };
};

这篇关于使用Javascript更改网页的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆