簡體   English   中英

使用 JavaScript,如果 URL 中提供了 id,我如何突出顯示標簽

[英]Using JavaScript, How do I highlight a tag if the id is provided in URL

<a href="#apple">apple</a>
<a href="#orange">orange</a>

我想要實現的是,使用純js,

  • 突出顯示蘋果鏈接if (window.location.hash) = "#apple"
  • 突出顯示橙色鏈接if (window.location.hash) = "#orange"

首先,您需要使用 javascript 獲取 DOM 元素。 這可以通過多種方式完成,但為簡單起見,我將使用 querySelector 進行展示。

anchors = document.querySelector('a')

所以變量anchors將有一個上面兩個anchor的NodeList。 讓我們把它們做成一個數組。

anchors_array = Array.prototype.slice.call(anchors)

現在讓我們遍歷這個數組並進行邏輯檢查,看看 hash 是否等同於 href。

for(let i = 0; i < anchors_array.length; i++)
  if(anchors_array[i].href === window.location.hash)
    // highlight code here.

 const loc = window.location.href; console.log(loc); //gets location const values = loc.split('/'); const link = values[values.length-1]; //split on mark / to get last part of the location const links = document.querySelectorAll("a"); //get all links //on click event for all links, removes active class if added before for(var i = 0, len = links.length; i < len; i++) { links[i].onclick = function () { [].forEach.call(links, function(el) { el.classList.remove("active"); }); }; }; // adds active class for clicked link or if current location. links.forEach(links => { if (links.href.endsWith(link)) { links.classList.add("active") }; links.addEventListener("click", () => links.classList.add("active")) });
 .active{ text-decoration: none; color: red; }
 <a href="#apple">apple</a> <a href="#orange">orange</a> <a href="js">js</a>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM