简体   繁体   中英

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

I have a website using WordPress, a theme and slider revolution. I'd like for a hyperlink in the mobile menu to change the font based on the URL. Example, if a user is currently on /about, the css font property is changed using jquery/javascript.

I'd like to know what JS/jquery code to use and how to add into WordPress?

Apologies but I'm new to JS/jquery

Thanks

Let's say you have a menu with a CSS class.menu like this:

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

To get the page url your visitor on:

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

Then save your menu links somewhere:

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

This is a NodeList so we can use forEach to see which one is the you need:

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.
  }
}

Based on your question, something like this might solve your solution. It's in Vanilla JS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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