[英]Changing the CSS of a file included with PHP using JavaScript
我最近在一个站点上创建了一个导航栏,该导航栏包含在使用PHP的页面中。
<?php include "Assets/Inclusions/NavigationBar.php" ?>
我希望活动页面列表项具有粗体文本,因此我使用JavaScript来获取当前路径,并使用许多if语句使相对元素变为粗体。
<script>
if(location.pathname == 'location.php')
document.getElementById("location").style.fontWeight="800";
} ...and so on
</script>
我应该有更好的方法吗?
这似乎是应该在服务器端完成的事情。 如果我犯了语法错误,请随时进行更正,自编写PHP以来已经有一段时间了,但这是要点:
NavigationBar.php
<?php
function isActive($page){
$currentPage = $_GET['page']; // mypage.com?page='something'
if ( !isset($currentPage) ) $currentPage = 'home';
return $currentPage == $path;
}
?>
<ul class="navigation">
<li><a href="?page=home"
<?php if ( isActive('home') ) echo('class="active"'); ?> >Home</a></li>
<li><a href="?page=About"
<?php if ( isActive('about') ) echo('class="active"'); ?>>About Us<a/></li>
</ul>
style.css文件
a.active{
font-weight: 800;
}
您可以使用for循环,获取导航中的所有链接元素,然后将路径与href进行比较。
var path = window.location.pathname;
var links = document.getElementsByClassName("navlink");
for(var i=0; i<links.length; i++){
if(links[i].getAttribute("href")==path){
links[i].style.fontWeight = "800";
break;
}
}
显然,您将必须针对您的情况进行正确的比较,但这将比编写大量ifs容易,并且由于不必对测试位置进行硬编码而更易于维护。
而且,如果您不担心与旧版浏览器的兼容性或使用jQuery,则可以将属性选择器与document.querySelector
或jQuery一起使用
//With querySelector
var link = document.querySelector("a[href='"+path+"']");
if(link!==null){
link.style.fontWeight=="800";
}
//with jQuery
$("a[href='"+path+"']").css("font-weight","800");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.