javascript 通过javascript函数改变颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6235224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:00:55  来源:igfitidea点击:

changing color by javascript function

javascripthtml

提问by alia

In the following code , I have a javascript function and I am tring to change the backgroundColor of the page to a color passed in as a parameter. But my code doesn't work, can anybody help me what is wrong in my code?

在下面的代码中,我有一个 javascript 函数,我想将页面的 backgroundColor 更改为作为参数传入的颜色。但是我的代码不起作用,有人可以帮助我我的代码有什么问题吗?

HTML:

HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Changing Color</title>
<head>
    <style type="text/css">
        body {
            background-color:#ffcccc;
        }
    </style>
</head>
<body>
    <form>
        <label>color: <input type="text" name="color"> </label>
        <input name="color" type = "button" onClick = "changecolor(color.value) " value = "color">
    </form>
</body>
</html>

Javascript:

Javascript:

function changecolor(colour)
{
    document.bgcolor=colour;
}

回答by Frédéric Hamidi

Assuming colourcontains a valid CSS color descriptor, you can write:

假设colour包含一个有效的 CSS 颜色描述符,你可以这样写:

document.body.style.backgroundColor = colour;

回答by mightyplow

you have to put the function in a script block.

你必须把函数放在一个脚本块中。

...

...

</form>
<script type="text/javascript>
  //function declaration 
</script>

回答by Bimal Sharma

Try this code it works finely man .i have just tried it.you can use it where-ever you want.also appended the code for onmouse click and onmouseover.

试试这个代码,它工作得很好,伙计。我刚刚试过了。你可以在任何你想要的地方使用它。还附加了 onmouse click 和 onmouseover 的代码。

<html>
    <head>
    <script language="javaScript">
    function change_background(color){
    document.bgColor = color;
    }
    </script>
    </head>
    <body>
    <form> 
    <label>color: <input type="text" name="color" > 
    </label>
    <input name="clrs" type ="button" value="getcolor" onClick = "change_background(color.value) " > 
    </form>
    <a href="#" onClick="change_background('#099')">ClickBlue</a>
    <a href="#" onMouseOver="change_background('#111')">Mouseoverblack</a>
    <a href="#" onMouseOver="change_background('#fff')">Mouseover white</a>
    </body>
    </html>`