第一種就是用的jqery的 load 方法 也是公認最好的方法
$("#header").load("page/header.html");
參考代碼
<body>JavaScript <div id="header"></div> <div id="footer"></div> <script> $("#header").load("page/header.html");//load 方法參數是引入公共文件的路徑 $("#footer").load("page/footer.html"); </script> </body>
但是這個方法有個弊端 就是會出現跨域
如果出現下面的報錯信息 就是出現了跨域問題
No 'Access-Control-Allow-Origin' header is present on the requested resource;
是因為load用的ajax,跨域會報錯。如果是本地file測試,不要用webkit核心瀏覽器如chrome,否則要發布網站通過http協議訪問
但是有解決辦法
- 就是把公共的HTML文件放在服務器中就可以了
- 在公共文件中 html,head,body這種標簽,要去掉
iframe 標簽的方法
參考代碼
<head> </head> <body> <div id="header"> <iframe align="center" width="100%" height="170" src="header.html" frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling="no"></iframe> </div> <div id="fotter"> <iframe align="center" width="100%" height="170" src="fotter.html" frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling="no"></iframe> </div> </body>
src 就是引入文件地址
注意:
body{margin:0; padding:0;}
要去除默認樣式 要不然會有留白。
這兩種就可以解決問題了 其他的都太坑了