douchunsui2395 2010-08-26 13:03
浏览 114
已采纳

在CSS中嵌入PHP

I'm trying to create a variable background, where the image changes based on the time of day. This code I have USED to work, but I did something somewhere along the line and didn't notice that the functionality had broken. Can someone explain to me why this doesn't work?

<html>
<?php

    function day()
    {
        if ( $hour >= 6 && $hour <= 18 )
        {
        return 1;
        } else { return 0; }
    }

?>

<style type="text/css">

body
{

    background-image: url('<?php echo (day() ? 'images/day_sheep.jpg'
                                             : 'images/night_sheep.jpg'); ?>');
    background-position: 50% 50%;
    background-repeat: no-repeat;
    background-color: silver
}

a {text-decoration:none;}
a:link {color:#ff0000;}
a:visited {color:#0000FF;}
a:hover {text-decoration:underline;}

</style>

</html>
  • 写回答

2条回答 默认 最新

  • doushaqing7080 2010-08-26 13:07
    关注

    Inside your function day(), $hour is unset. It will be treated as 0 in a numerical context, and if you enable reporting of notices, you will see notices warning you of an unset variable. Did it used to be a global variable? Did you remove code that set its value or declared it as global?

    Edit: Also, on a point of style, I feel it would look neater to have an external CSS file like this:

    body {
        background-position: 50% 50%;
        background-repeat: no-repeat;
        background-color: silver
    }
    
    body.day {
        background-image: url('images/day_sheep.jpg');
    }
    
    body.night {
        background-image: url('images/night_sheep.jpg');
    }
    

    and then you can get rid of the CSS section of your php script, but include the above CSS file, and you need only have the following:

    <body class="<?php echo day() ? 'day' : 'night'; ?>">
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样