如何在标签内使用 PHP 添加 css 文件<head>?



好的,让我解释一下:

我有一些文件,像这样基本的东西:

索引.php

<html>
      <head>
            <title>Simple page</title>
      </head>
      <body>
            <?php include 'home.php'; ?>
      </body>
</html>

首页.php

<div class="thisWillBeBlue">Still not blue</div>

风格.css

.thisWillBeBlue {background: blue}

现在的问题:使用 php 我想在 head 标签内插入样式.css从文件 home.php 调用它。好吧,我想出了一个解决方案,但它不是很有效:

索引.php

<?php $css = array(); 
      $css[] = 'linktothecss.css'
?>
<html>
      <head>
            <title>Simple page</title>
            <?php
                foreach($css as $item){
                    echo "<link rel='stylesheet' href='".$item."' />";
                }
            ?>
      </head>
      <body>
            <?php include 'home.php'; ?>
      </body>
</html>

但问题是,如果我从家里调用 css.php它稍后会被添加到数组中,因此它不会在 head 标签内回显。有什么想法吗?

您可以使用

ob_start()ob_end_flush()函数来做到这一点例如

索引.php

<?php
$csspage = "default.css";
function loadCSS($buffer) {
  global $csspage;  
  return (str_replace('{{ css }}', $csspage, $buffer));
}
ob_start("loadCSS"); ?>
<html>
   <head>
      <!-- the string {{ css }} is just a placeholder that will be replaced 
           with the new value of $csspage defined later in the code, otherwise
           it will replaced with its initial value (default.css)
      -->
      <link href="{{ css }}" /> 
   </head>
<body>
     <?php include 'home.php'; ?>
</body>
</html>
<?php ob_end_flush(); ?>

首页.php

 <?php $csspage = "custom_style.css";  ?> 
 <div class="thisWillBeBlue">blue</div>

进一步参考:http://it1.php.net/ob_start

我想你正在寻找这样的东西..(在他们的头文件中包括一段代码,以便允许您添加更多样式表)

这将允许您在每个页面上添加更多样式表。(将此添加到<head>

<?php
if (!empty($styles) && is_array($styles)) {
    foreach ($styles AS $style) {
        echo '<link rel="stylesheet" href="/assets/css/'. $style .'">';
    }
}
?>

如果需要特定的样式表,可以将变量放在单个脚本的顶部:

如果需要,
<?php
$styles = array('custom_style.css');
?>
可以将

CSS 文件引用放在代码正文中。

<body>
  <link href="linktothecss.css" rel="stylesheet" type="text/css" />
  <div class="thisWillBeBlue">
    I'll be blue as soon as linktothecss.css finishes loading!
  </div>
</body>

唯一的区别是,在 HEAD 中时,保证在呈现页面之前加载它们。当它们在 BODY 中时,可能会有一瞬间它们仍在加载并且样式尚未应用。

如果你肯定想在 HEAD 中,你可以在一个具有相同文件名的单独文件夹中定义 css 要求,如下所示:

索引.php:

<html>
  <head>
    <?php
    include('css-requirements/home.php');
    ?>
  </head>
  <body>
    <?php include('home.php'); ?>
  </body>
</html>

css-requirements/home.php:

<link href="mycss.css" rel="stylesheet" type="text/css" />
<link href="myothercss.css" rel="stylesheet" type="text/css" />

相关内容

最新更新