需求
幾個頁面需要的頭部和底部的内容往往是一樣的,這就希望可以隻寫一段代碼作為模闆,然後再幾個頁面中都加載這這個模闆。另外,如果需要修改,也隻要修改模闆就好,所有頁面都同時都是新的樣式了。
通過 JavaScript 來實作
能實作上面需求的方法還是不少的,這個比較簡單一點,幾乎不需要學習的額外知識,隻通過2句基本的js語句就能實作。一句寫頁面html,一句加載js檔案執行。暫時先用了這個方法。
第一步:制作html檔案
把你的代碼正常寫成一個html檔案,比如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div style="background: black;height: 36px;line-height: 36px;color: #9f9f9f;">
<div style="width: 1000px;margin: auto;">
<span>
歡迎光臨,請
<a rel="nofollow" href="login.html" style="text-decoration: none;color: red;">登入 </a>
或者
<a rel="nofollow" href="regist.html" style="text-decoration: none;color: red;">注冊</a>
</span>
<ul style="float: right;list-style-type: none;margin: 0">
<li style="float: left;margin: 0 5px;padding: 0 10px;">
<a rel="nofollow" href="cart.html" style="text-decoration: none;color: red;">購物車</a>
</li>
<li style="float: left;margin: 0 5px;padding: 0 10px;">我的訂單</li>
<li style="float: left;margin: 0 5px;padding: 0 10px;">客戶服務</li>
</ul>
</div>
</div>
</body>
</html>
第二步:轉成js檔案
document.writeln("<div style=\'background: black;height: 36px;line-height: 36px;color: #9f9f9f;\'>");
document.writeln(" <div style=\'width: 1000px;margin: auto;\'>");
document.writeln(" <span>");
document.writeln(" 歡迎光臨,請");
document.writeln(" <a rel="nofollow" href=\'login.html\' style=\'text-decoration: none;color: red;\'>登入 </a>");
document.writeln(" 或者");
document.writeln(" <a rel="nofollow" href=\'regist.html\' style=\'text-decoration: none;color: red;\'>注冊</a>");
document.writeln(" </span>");
document.writeln(" <ul style=\'float: right;list-style-type: none;margin: 0\'>");
document.writeln(" <li style=\'float: left;margin: 0 5px;padding: 0 10px;\'>");
document.writeln(" <a rel="nofollow" href=\'cart.html\' style=\'text-decoration: none;color: red;\'>購物車</a>");
document.writeln(" </li>");
document.writeln(" <li style=\'float: left;margin: 0 5px;padding: 0 10px;\'>我的訂單</li>");
document.writeln(" <li style=\'float: left;margin: 0 5px;padding: 0 10px;\'>客戶服務</li>");
document.writeln(" </ul>");
document.writeln(" </div>");
document.writeln("</div>");
第三步:到你的頁面檔案中加載這個js檔案
<script src="page/pg-top.js"></script>