2014-02-20 45 views
1

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

<!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

欢迎来到堆栈溢出首先!其次,这个网站的主要目的是帮助您在遇到困难点时克服编程问题,并且无法通过它。要获得高质量的答案,请务必发布您尝试过的内容,您当前获得的结果以及期望的结果。你需要展示你目前试过的东西,我们不会为你做所有的工作。 – snollygolly

+0

http://jsfiddle.net/5H8ux/1/ – lshettyl

回答

3

试试这个:

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

http://jsfiddle.net/5H8ux/

尝试类似#000000#fff

+0

没有颜色代码,但是当我输入任何颜色名称似乎工作,如何? – user3334606

+1

JavaScript也会[颜色名称](http://www.w3schools.com/tags/ref_colornames.asp)。任何十六进制值都可以工作,如果你想成为真正的OCD,你可以创建一个[list of colors](http://stackoverflow.com/questions/1573053/javascript-function-to-convert-color-names-to -hex-codes)来验证是否输入了可接受的颜色名称。如果它是6个字符的十六进制值,则是有效的。 – StephenH

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

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> 
+1

为什么切换?请解释! – lshettyl

+0

没有注意到。编辑它。 –

+0

控制提示输入并只允许少量颜色 –

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指出的图书馆看起来不错。