如何使用Javascript更改背景颜色?

时间:2014-02-20 21:00:18

标签: javascript html css

我想使用用户输入更改页面的背景颜色。到目前为止这是我的代码..

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<script type = "text/javascript">
function paintIt(){
    color = prompt("Enter the color you want on the Background???");
    switch (color){
    }
}
</script>
<form>
<input type = "button" value = "Paint Me" onclick ="paintIt()">
</form>
</body>
</html>

和我的简单css

   html {font-family:Arial, Helvetica, sans-serif; colour:#fff;}
            body{background-color:#ccc; margin:0;}

由于

5 个答案:

答案 0 :(得分:5)

function paintIt()
{
    color = prompt("Enter the color you want on the Background???");
    document.body.style.backgroundColor = color;
}

http://jsfiddle.net/5H8ux/

尝试类似#000000#fff的内容。

答案 1 :(得分:3)

试试这个:

function paintIt(){
   document.body.style.backgroundColor = "red";
}

答案 2 :(得分:2)

试试这个

function paintIt(){ 
    color = prompt("Enter the color you want on the Background???"); 
    document.body.style.backgroundColor = color;
}

<强> Js Fiddle Demo

您可以尝试使用此RGB Color Parser来验证不同格式的颜色名称,无论它们是否为有效颜色。这是demo

答案 3 :(得分:2)

一个简单的例子,希望用户输入有效的背景颜色:

<button id="my-button">Change background</button>
<script>
    document.getElementById("my-button").addEventListener("click", function() {
        document.body.style.backgroundColor = prompt("What color");
    });
</script>

JSFiddle:http://jsfiddle.net/XLL3n/1/

我没有代表。所以我无法评论,但你应该考虑reading about css colors来理解可能的有效输入。 @Sachin指出的图书馆看起来不错。

答案 4 :(得分:1)

<script type = "text/javascript">
function paintIt(){
    color = prompt("Enter the color you want on the Background???");
    switch (color){
        case "red":
            document.body.style.background = color;
        break;
        case "white":
            document.body.style.background = color;
        break;
        default: alert("not a valid color");
   }
}
</script>
相关问题