如何在PHP中编写以下内容:
如果当前页面的名称为
pagex.php
然后请加载这些额外的CSS规则:
#DIVS{color:#FFF}
如果当前页面的名称为anotherpage.php
然后请加载以下CSS规则:
#DIVS{color:#000}
如下:
<?php
if (basename(__FILE__) == 'pagex.php') {
echo '#DIVS { color:#FFF }';
} else if (basename(__FILE__) == 'anotherpage.php') {
echo '#DIVS { color:#000 }';
}
?>
PHP有一些"神奇常数",您可以通过检查来获得这些信息。看看`__FILE__常量。
文件的完整路径和文件名。如果在include中使用,则会返回包含文件的名称。自PHP 4.0.2以来,FILE总是包含一个解析了符号链接的绝对路径,而在旧版本中,在某些情况下它包含相对路径。
因此,您可以使用这个__FILE__
变量,并对其执行basename()
函数来获取文件名。basename()
函数返回路径的尾部名称组件。然后你只需做一个开关案例来匹配所需的值-
$fileName = basename(__FILE__);
switch($fileName){
case 'pagex.php':
echo '<link .... src="some_stylesheet_file.css" />';
break;
case 'anotherpage.php':
echo '<link .... src="another_stylesheet_file.css" />';
break;
}
您的附加CSS规则可以位于这些单独的文件中。
或者,如果你不想将css拆分为多个文件,你可以将这些特定的规则回声到页面的头部元素中,比如
echo '<style type="text/css">';
$fileName = basename(__FILE__);
switch($fileName){
case 'pagex.php':
echo '#DIVS { color:#FFF }';
break;
case 'anotherpage.php':
echo '#DIVS { color: #000 }';
break;
}
echo '</style>';
参考资料-
basename()
- php魔术常量
您只需在HTML头部分添加一个PHP if…else即可根据页面名称加载额外的样式表。
<head>
<?php
if (basename(__FILE__) == 'one.php')
echo '<link .... src="style1.css" />';
elseif (basename(__FILE__) == 'two.php')
echo '<link ..... src="style2.css" />';
?>
</head>
您可以以自定义的方式使用wordpress的is_page()函数,因为它正在处理常规php.code is:
<?php
$baseurl = 'http://www.example.com'; //set the base url of the site
$mypage1 = $baseurl."/pagex.php"; //add the rest of the url
$mypage2 = $baseurl."/anotherpage.php"; //add the rest of the url
$currentPage = $baseurl.$_SERVER['REQUEST_URI'];// this gets the current page url
if($currentPage==$mypage1) {
//do something with you style or whatever..
}
else if($currentPage==$mypage2)
{
//do something with you style or whatever..
}
?>
你必须根据自己的需要改变它。我想这会对你有所帮助。快乐的编码!