繁体   English   中英

如何使用 Jquery/JS 更改基于 URL 的 Wordpress 中的 CSS 属性?

[英]How can I use Jquery/JS to change CSS property in Wordpress based on URL?

我有一个使用 WordPress、主题和 slider 革命的网站。 我想要移动菜单中的超链接来更改基于 URL 的字体。 例如,如果用户当前在 /about,则使用 jquery/javascript 更改 css 字体属性。

我想知道要使用什么 JS/jquery 代码以及如何添加到 WordPress 中?

抱歉,但我是 JS/jquery 的新手

谢谢

假设您有一个带有 CSS class.menu 的菜单,如下所示:

<ul class='menu'>
  <li><a href="index.html">Home</a></li>
  <li><a href="aboutus.html">About Us</a></li>
</ul>

要获取页面 url 您的访客:

let currentURL = window.location.href.split('/').pop(); //Gets the url, splits it by / and return the last piece which is the URL you need.

然后将您的菜单链接保存在某处:

let menuLinks = document.querySelectorAll('.menu a');

这是一个 NodeList,因此我们可以使用 forEach 来查看您需要哪一个:

menuLinks.forEach(link => {
  if(link.href.includes(currentURL)) {
    //You can add inline styling like this
    link.style.fontFamily = "Arial";
    link.style.fontWeight = "Bold";
    // Or you can add another class name to the element
    link.classList.add('currentUrlStyle'); // You need to style .currentUrlStyle selector in your css file.
  }
}

根据您的问题,这样的事情可能会解决您的解决方案。 它在香草 JS 中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM