簡體   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