我有一个 HTML 页面,主体做的第一件事是包含顶部横幅 div 和导航栏 div:
主 html 文件的正文:
<?php
require_once "article_functions.php";
include "widgets/topborder.html";
include "widgets/banner.php";
include "widgets/navbar.html";
?>
每个包含的结构都相同,一个 div 和样式:
<style type="text/css">
#banner_area {
height:30px;
width: 100%;
float:left;
background-color:#00A54D;
margin-top:0px;
}
.text {
font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
color:white;
margin-left:250px;
display:inline;
}
.icons {
float:right;
width: 30px;
height: 30px;
margin-right: 5px;
}
a.text:link {
text-decoration:none!important;
}
</style>
<div id="banner_area">
<p class="text"><a href="http://example.org"> example.org </a></p>
<img class="icons" src="http://example.org/--folder-/48x48/email.png" alt="Email button">
</div>
我在无样式内容闪烁方面遇到了一些问题,我认为这是因为 <style>
上面的标签不在 <head>
中,但我真的很想在这些 PHP 文件中保留样式,有什么方法可以使样式正确加载到头部吗?
最佳答案
是的,它适用于输出缓冲和 HTML 标准。
首先你需要启用输出缓冲:
<?php
ob_start(); // <<== Enabling output buffering
require_once "article_functions.php";
include "widgets/topborder.html";
include "widgets/banner.php";
include "widgets/navbar.html";
?>
然后当你完成时(在脚本的末尾),你在缓冲区中读回,解析 HTML 并将样式元素从 body 标记内移动到头部:
$buffer = ob_get_clean();
$doc = new DOMDocument();
$doc->loadHTML($buffer);
$head = $doc->getElementsByTagName('head')->item(0);
$xpath = new DOMXPath($doc);
foreach ($xpath->query('//body//style') as $bodyStyle) {
$head->appendChild($bodyStyle);
}
echo $doc->saveHTML();
这将根据您的更改输出 HTML:
<html><head><style type="text/css">
#banner_area {
height: 30px;
...
希望这对您有所帮助。
关于php - 将样式从 PHP 移动到头部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24110643/