简体   繁体   中英

Active font-weight with JS + CSS

I need to know how to activate font-weight on the page (I'm using JavaScript).

Example: If I'm on the teachers page, the <a> Teachers </a> font-weight should be bold like shown in image below.

在此处输入图像描述

<!DOCTYPE html>
<html>
   <head>

       {% block head %}
           <title>Private Classes</title>
       {% endblock %}

       <link rel="stylesheet" href="/styles.css">
   </head>

   <body>
       <header>       
           <div class="links">
               <a href="/" class="active">Teachers</a>
               <a href="/students">Students</a>
           </div>
       </header>       
       {% block content %}
       {% endblock %}

   </body>
</html>

You are on teachers page and 'active' class is already there so no need to use javascript for it. Simply adding font weight to the 'active' class is enough.

<style>
.active{
  font-weight: bold;
}
</style>
const currentPage = location.pathname
const menuItems = document.querySelectorAll("header .links a")

for (item of menuItems) {
    if (currentPage.includes(item.getAttribute("href"))) {
        item.classList.add("active")
    }
}

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