jquery 在不在特定页面上时应用样式

我正在尝试将一种样式应用到我的导航栏,特别是当我在索引页面以外的任何页面上时,但我似乎无法让它工作,我不确定问题是什么。


这是我的脚本:


$(document).ready(function(){

  if (window.location.pathname != "") {

    $('#main-nav').css('background-color', 'black');

  }

});

如果重要的话,我正在使用 Angular 10。


函数式编程
浏览 79回答 3
3回答

慕村9548890

您没有提到索引的路径是什么。我猜它可能是“/”或“索引”。检查您的索引路径,然后比较代码中的路径if (window.location.pathname != ""     || window.location.pathname != "/"        || window.location.pathname != "index") {            $('#main-nav').css('background-color', 'black');}

Smart猫小萌

由于您使用的是 Angular 10,因此您可以使用路由器并添加样式,这非常容易。Angular Router 在你的 component.ts 文件中注入 Angular 路由器Constructur(public router: Router){  //After Logging check the url string and add it to the ngClass condition  console.log(router.url);}然后在你的 html 文件中,在你的案例中,将 navbar html 文件添加到 navbar 标签中,添加 ngClass。NgClass 指令[ngClass]="{'customStyle': router.url=== '/'}"在您的导航栏组件 css 文件中。.customStyle{background-color: "black"}

慕标琳琳

请试试这个:$(document).ready(function(){  if (window.location.pathname != "" || window.location.pathname.indexOf("index")>0) {    $('#main-nav').css('background-color', 'black');  }});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript