如何在我的HTML中使我的导航栏相同?

BBM*_*225 27 html

每个新页面我都要更新导航面板.这意味着我会在页面之间复制并粘贴导航栏.我添加的页面越多越难.现在我有一致的导航栏.所以我正在寻找一种方法来制作一个只包含导航栏的html文件,然后将其嵌入到我的代码中,就像我使用CSS和JavaScript一样.这样,如果我编辑一个文件,所有其他页面都会更新.如果我使用iframe标签会遇到许多问题,但我知道没有其他标签可以做我需要的.所以我该怎么做?我做了一些研究,但我能找到的只是iframe标签..我该怎么办?

Fil*_*ikj 14

如果您的页面严格是HTML + JavaScript,则可以使用HTML DOM innerHTML属性.这是一个例子:

的index.html

 <body>
  <nav id="navMenu"></nav>
  <div> rest of web page body here </div>
  <script src="script.js"></script>
 </body>
Run Code Online (Sandbox Code Playgroud)

about.html

 <body>
  <nav id="navMenu"></nav>
  <div> rest of web page body here </div>
  <script src="script.js"></script>
 </body>
Run Code Online (Sandbox Code Playgroud)

的script.js

 document.getElementById("navMenu").innerHTML =
 '<ul>'+
  '<li><a href="index.html">Home</a></li>'+
  '<li><a href="services.html">Services</a></li>'+
  '<li><a href="about.html">About</a></li>'+
 '</ul>';
Run Code Online (Sandbox Code Playgroud)

这里重要的一行是nav标签,您需要做的就是在此示例about.html中的其他页面中添加此行.

我也推荐PHP或类似的东西来完成你需要的东西!


BBM*_*225 0

我自己弄清楚了,你可以使用 JavaScript 文件并使用 document.write 然后将其放在你想要的位置:

<script type="text/javascript" src="/js/sidebar.js"/>
Run Code Online (Sandbox Code Playgroud)

这是我的 js 文件:

document.write("<div id='sidebartop'>");
document.write("<p>Navigation</p>");
document.write("</div>");
Run Code Online (Sandbox Code Playgroud)

如果您想在行内同时使用双引号和单引号,请小心,我认为 < 和 > 符号必须位于双引号中。这是我的完整代码:

     ----/js/sidebar.js----
document.write("<div id='sidebartop'>");
document.write("<p>Navigation</p>");
document.write("</div>");
document.write("<div id='sidebar'>");
if (page==1) { var p=" style='text-decoration: underline;'" } else { var p=" style='text-decoration: normal;'" }
if (page==2) { var pp=" style='text-decoration: underline;'" } else { var pp=" style='text-decoration: normal;'" }
if (page==3) { var ppp=" style='text-decoration: underline;'" } else { var ppp=" style='text-decoration: normal;'" }
if (page==4) { var pppp=" style='text-decoration: underline;'" } else { var pppp=" style='text-decoration: normal;'" }
if (page==5) { var ppppp=" style='text-decoration: underline;'" } else { var ppppp=" style='text-decoration: normal;'" }
document.write("<p><"+'a href="http://brandonc.handcraft.com/"'+p+">Home</a></p>");
document.write("<p><"+'a href="http://brandonc.handcraft.com/about"'+pp+">About The Author</a></p>");
document.write("<p><"+'a href="http://brandonc.handcraft.com/sevenmages"'+ppp+">The Seven Mages</a></p>");
document.write("<p><"+'a href="http://brandonc.handcraft.com/comment"'+pppp+">Leave A Comment</a></p>");
document.write("<p><"+'a href="http://brandonc.handcraft.com/calender"'+ppppp+">Calender</a></p>");
document.write("</div>");

     ----In place where you want code to go----
<script>var page=5</script>
<script type="text/javascript" src="/js/sidebar.js"/>
Run Code Online (Sandbox Code Playgroud)

可能不是最有效的,我强烈建议像其他答案一样使用 PHP,但这对我有用,并且不需要在每个 url 后添加 .php。