HTML不同页面中重用代码
2018-02-24 19:55
633 查看
需求
几个页面需要的头部和底部的内容往往是一样的,这就希望可以只写一段代码作为模板,然后再几个页面中都加载这这个模板。另外,如果需要修改,也只要修改模板就好,所有页面都同时都是新的样式了。通过 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 href="login.html" style="text-decoration: none;color: red;">登录 </a> 或者 <a 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 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(" ")包起来。把你的html的内容都写在括号里。例外注意引号需要用
\"转义。这个工作写个简单的脚本就能完成、不过也有现成的在线工具:http://tool.chinaz.com/Tools/Html_Js.aspx
最后你的js文件是这样的,这里我只需要body内的部分:
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 href=\'login.html\' style=\'text-decoration: none;color: red;\'>登录 </a>"); document.writeln(" 或者"); document.writeln(" <a 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 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文件
把这句放在你的body的第一行,这样的的头部内容就有了:<script src="page/pg-top.js"></script>
相关文章推荐
- asp.net 中将表单提交到另一页 Code-Behind(代码和html在不同的页面)
- html页面代码重用
- 不同html页面 相同部分代码的提取
- asp.net 中将表单提交到另一页 Code-Behind(代码和html在不同的页面)
- 同一html页面中不同链接的不同样式的css代码
- asp.net 中将表单提交到另一页 Code-Behind(代码和html在不同的页面)
- asp.net 中将表单提交到另一页 Code-Behind(代码和html在不同的页面)
- html页面音乐播放器_embed代码
- PHP生成HTML静态页面实例代码
- 在ASP.NET 2.0中直接得到本页面生成的HTML代码
- html页面插入flash代码
- 多个轮播图或者选项卡显示在一个页面是,使用代码重用
- HTML--如何实现通过鼠标事件拖动页面图像(代码)
- 如何让不同的HTML代码适应不同的浏览器
- 爬虫技术 -- 进阶学习(九)使用HtmlAgilityPack获取页面链接(附c#代码及插件下载)
- 在ASP.NET中,后台代码向页面写HTML代码
- 打开html页面执行js代码
- Server.HTMLEncode让代码在页面里显示为源代码
- Server.HTMLEncode让代码在页面里显示为源代码
- 【HTML】根据不同的浏览器类型写不同的HTML代码