繁体   English   中英

PHP将样式表添加到标题

[英]PHP Adding stylesheets to header

在包含头文件后,有没有办法将样式表添加到标题? 说我们有这个代码:

class content {
    public $stylesheets = array();

    public function addStylesheets($stylesheets)
    {
        if(!empty($stylesheets))
        {
            if(!is_array($stylesheets))
                $stylesheets = array($stylesheets);

            $this->stylesheets = array_merge($this->stylesheets, $stylesheets);
        }
    }

    public function getStylesheets()
    {
        $response = '';

        foreach($this->stylesheets as $stylesheet)
            $response .= '<link rel="stylesheet" type="text/css" href="' . $stylesheet . '" />' . Chr(13);

        return $response;
    }
}

这个标题:

<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" type="text/css" href="default.css" />
    <?php
        print($content->getStylesheets());
    ?>
</head>

<bod...

然后在文件中我想添加样式表:

$content->addStylesheets(array('home.css', 'slider.css'));

有人能给我一个如何做到这一点的例子吗?

最终的html代码总是在最后生成。 这是一个如何继续使用纯php / html的示例。 你的index.php看起来像这样:

<?php

// ...

// Define the stylesheets to use
$content = new content();
$content->addStylesheets(array('home.css', 'slider.css'));

// ...

// Print template at the end
ob_start();
include 'your_html_template.php';
print ob_get_clean();

your_html_template.php是您的模板文件,如问题所示。


您可以在执行模板之前定义变量 ,以便更清楚地分离php代码和html 然后index.php看起来像这样:

<?php

// ...

// Define the stylesheets to use
$content = new content();
$content->addStylesheets(array('home.css', 'slider.css'));
$htmlStyleHeaderTags = $content->getStylesheets();  // Define variable with html header tags

// ...

// Print template at the end
ob_start();
include 'your_html_template.php';
print ob_get_clean();

然后您可以在模板中使用变量$htmlStyleHeaderTags

<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" type="text/css" href="default.css" />
    <?php print $htmlStyleHeaderTags; ?>
</head>

<bod...

由于@szapio已经很伤心,因此在最后构建HTML更有意义。

无论如何,一个“脏”的解决方案是使用jQuery来破解你的DOM,方法是在</body> -tag之前添加以下内容(在<head>包含jQuery):

<script>
$(document).ready(function() {
    $('head').append('<link rel="stylesheet" href="test.css" />');
});
</script>

你真的不应该考虑这样做,因为CSS文件将在其他所有内容之后加载,这意味着只要尚未加载CSS文件,你就会看到没有样式的元素......

暂无
暂无

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

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