如何根据输入的值更改Javascript中的背景颜色

时间:2012-09-30 05:30:48

标签: php javascript

我正在尝试创建一个页面,当进入或高于70的温度时,结果页面将变为红色,如果温度低于70,则它将变为蓝色。我已经有了提交页面代码的第一部分的示例页面。我只是不希望单词变成颜色,我希望整个页面根据温度变成颜色。有人可以帮忙吗?

<html>
<body>
<?php
if (isset($_POST['temperature'])): //isset determines if var has valid contents, even empty string

    //if var is set, show what it contains
    $myFahrenheit = (int)$_POST['temperature']; //cast value sent via post to an integer

    $myCelsius = intval(($myFahrenheit-32) * (5/9)); //calc celsius
    echo '<h1><font color="blue">You entered ' . $myFahrenheit . ' in Fahrenheit!!</font><br />';
    echo '<h1><font color="red"> It is '. $myCelsius .' in celsius!!</font><br />';
    //put link on page to reset form
    print '<a href="' . $_SERVER['PHP_SELF'] . '">Reset page</a>';
else:
    //show form
?>
    <!--Note the server variable indicating the page we are on -->
    <form action="<? print $_SERVER['PHP_SELF']; ?>" method="post">
    Enter your temperature in Fahrenheit <input type="text" name="temperature"><br>
    <input type="submit" value="Show me the temperature in celsius!!">
    </form>
<?
endif;
?>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

我想一个简单的<body>样式会在这里起作用吗?

<html>
<?php
    $style = '';
    if (isset($_POST['temperature']))
    {
        if ($_POST['temperature'] >= 70)
            $style = 'background-color: red;';
        else
            $style = 'background-color: blue;';
    }
?>
<body style="<?php echo htmlspecialchars($style); ?>">

答案 1 :(得分:0)

像这样使用

<html>
<?php
if (isset($_POST['temperature'])) //isset determines if var has valid contents, even empty string
{//if var is set, show what it contains
$myFahrenheit = (int)$_POST['temperature']; //cast value sent via post to an integer
if($myFahrenheit > 70)
   echo "<body style='background-color:red;'>";
else
   echo "<body style='background-color:blue;'>";
$myCelsius = intval(($myFahrenheit-32) * (5/9)); //calc celsius
 echo '<h1><font color="blue">You entered ' . $myFahrenheit . ' in Fahrenheit!!    </font><br />';
echo '<h1><font color="red"> It is '. $myCelsius .' in celsius!!</font><br />';
//put link on page to reset form
print '<a href="' . $_SERVER['PHP_SELF'] . '">Reset page</a>';
}else{ //show form
?>

答案 2 :(得分:0)

if($myFahrenheit > 70)
  echo '<script>document.body.style.background = "red";</script>';
else
  echo '<script>document.body.style.background = "blue";</script>';