简体   繁体   English

在PHP中设置背景颜色?

[英]Set background color in PHP?

在PHP中设置背景颜色的最简单方法是什么?

只需插入以下行并使用您喜欢的任何颜色

    echo "<body style='background-color:pink'>";
<?php
    header('Content-Type: text/css');
?>

some selector {
    background-color: <?php echo $my_colour_that_has_been_checked_to_be_a_safe_value; ?>;
}

You must use CSS. 你必须使用CSS。 Can't be done with PHP. 无法用PHP完成。

CSS supports text input for colors (ie "black" = #000000 "white" = #ffffff) So I think the helpful solution we are looking for here is how can one have PHP take the output from an HTML form text input box and have it tell CSS to use this line of text for background color. CSS支持颜色的文本输入(即“黑色”=#000000“白色”= #ffffff)所以我认为我们在这里寻找的有用解决方案是如何让PHP从HTML表单文本输入框中获取输出并具有它告诉CSS使用这行文本作为背景颜色。

So that when aa user types "blue" into the text field titled "what is your favorite color", they are returned a page with a blue background, or whatever color they happen to type in so long as it is recognized by CSS. 因此,当用户在标题为“您最喜欢的颜色是什么”的文本字段中键入“蓝色”时,只要它被CSS识别,它们就会返回一个蓝色背景的页面,或者它们输入的任何颜色。

I believe Dan is on the right track, but may need to elaborate for use PHP newbies, when I try this I am returned a green screen no matter what is typed in (I even set this up as an elseif to display a white background if no data is entered in the text field, still green? 我相信Dan在正确的轨道上,但可能需要详细说明使用PHP新手,当我尝试这个时,无论输入什么,我都会返回绿色屏幕(我甚至将其设置为elseif以显示白色背景,如果没有数据输入文本字段,仍为绿色?

You can use php in the style sheet. 您可以在样式表中使用php。 Just remember to set header("Content-type: text/css") in the style.php (or whatever then name is) file 只记得在style.php(或其他名称)文件中设置标题(“Content-type:text / css”)

This really depends on what you need to do. 这实际上取决于你需要做什么。 If you want to set a background colour on a page then you need to use CSS as per Jay's and David Dorward's answers. 如果你想在页面上设置背景颜色,那么你需要根据Jay和David Dorward的答案使用CSS。

If you are building an image with PHP then you can use the GD library to allocate colours yourself. 如果使用PHP构建映像,则可以使用GD库自行分配颜色。 I don't recommend this without thoroughly reading up on how to create images with GD. 如果不仔细阅读如何使用GD创建图像,我不建议这样做。 http://www.php.net/manual/en/function.imagecolorallocate.php http://www.php.net/manual/en/function.imagecolorallocate.php

Try this: 尝试这个:

<style type="text/css">
  <?php include("bg-color.php") ?>
</style>

And bg-color.php can be something like: 而bg-color.php可以是这样的:

<?php
//Don't forget to sanitize the input
$colour = $_GET["colour"];
?>
body {
    background-color: #<?php echo $colour ?>;
}

You better use CSS for that, after all, this is what CSS is for. 你最好使用CSS,毕竟这就是CSS的用途。 If you don't want to do that, go with Dorwand's answer. 如果您不想这样做,请使用Dorwand的答案。

我建议使用css,但php用于为元素设置一些类或id,以使其动态生成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM