我正在网站上工作,我厌倦了将页眉和页脚复制/粘贴到每个页面,因为当您需要更改一个字母时,您必须使用该页眉/页脚在所有页面上更改它。所以我'复制'了我从Laravel学到的功能,偏。
我在一个文件中编写标题的HTML,然后使用PHP将其加载到页面。
我的标题代码:
<div class="header">
<div class="header-wrapper">
<a href="index.php">
<img class="logo" src="images/logo.png" />
</a>
<ul>
<li><a onload="highlight(this);" href="index.php">Home</a></li>
<li><a onload="highlight(this);" href="over.php">Over ons</a></li>
<li><a onload="highlight(this);" href="catalogus.php">Onze machines</a></li>
<li><a onload="highlight(this);" href="portfolio.php">Portfolio</a></li>
<li><a onload="highlight(this);" href="contact.php">Contact</a></li>
</ul>
</div>
</div>
<script>
//Highlight current
function highlight(obj) {
var page = location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
if (page == obj.getAttribute("href")) {
obj.classList.add("current");
}
alert(page);
alert(obj.getAttribute("href"));
}
</script>
CSS:
.current {
text-decoration: underline;
}
标题包含在以下页面中:
<?php
//Include header
$f = fopen("partial/header.html", "r");
echo fread($f, 4096);
?>
这是有效的,唯一的问题是我想在标题中显示用户所在的当前页面。这只是在标题中加下当前页面名称的下划线。
函数highlight()正在运行,但是onload无效。 似乎onLoad函数不支持anchor-tag。
我该如何解决这个问题?如何在onLoad上的每个锚标签上执行highlight() - 函数?
Javascript和JQuery允许,我没有使用框架。
答案 0 :(得分:1)
看起来你并没有使用Jquery&#39;我会保持简单的javascript
var page = location.pathname.substring(
location.pathname.lastIndexOf('/') + 1,
);
document.querySelectorAll('li > a').forEach(el => {
if (page == el.getAttribute('href')) {
el.classList.add('current');
}
});
为了解释这里发生了什么,我们在列表项中选择所有锚标签。我建议给列表class
,以便您可以在javascript中更好地识别它。
document.querySelectorAll('.nav a')
并将该类添加到HTML
<ul class="nav">
答案 1 :(得分:0)
感谢Mike指出我正确的方向。我能用一些JQuery修复它。
<script>
//Highlight current
function highlight(obj) {
var page = location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
if (page == obj.getAttribute("href")) {
obj.classList.add("current");
}
}
//Launch highlight function on document load
$(document).ready(function() {
$(".header-wrapper ul li a").each(function() {
highlight(this);
});
});
</script>
注意:您仍然需要处理www.mywebsite.com/将无法正常工作,因为它在网址中没有文件名,如www.mywebsite.con / index.php