簡體   English   中英

如何使用javascript更改超鏈接的活動顏色?

[英]How to change active color of hyperlink with javascript?

我正在嘗試使用 javascript 添加一堆 <p<a/a>/p> 元素,並希望使用 javascript 更改鏈接的活動顏色。 我該怎么做? 我無法在 css 文件中使用 a:active 更改所有超鏈接的顏色,因為我有一組其他鏈接,我想要不同的顏色,我目前正在使用 css 來解決這些問題。

這些是我通過 javascript 添加的內容:

    var supertag = document.createElement("p");
    var tag = document.createElement('a');
    var text = document.createTextNode("Join a New Community!");
    tag.appendChild(text);
    tag.href = "http://localhost:8088/communities_index/communities_index.html";
    tag.style.color = "blue";
    supertag.appendChild(tag);
    var element = document.getElementById("globalCommunities");
    element.appendChild(tag);

我可以將超鏈接的顏色更改為藍色,但隨后它會失去其在 css 中本來是紅色的活動顏色。 其他鏈接是黑色的,懸停時變為藍色,活動時變為紅色。 我希望新的超鏈接在活動時為藍色並變為紅色。

似乎沒有編程方式來定位 JavaScript 中的 CSS :active狀態。 一種方法是監聽相關鏈接上的mouseupmousedown事件,並通過樣式設置它們的顏色。

  // Grab your link, here an element with ID my-link
  var a = document.querySelector('#my-link');
  // Set mousedown event listener
  a.addEventListener('mousedown', () => {
    // Use style to set element color
    a.style.color = 'red';
  });
  // Set mouseup event listener
  a.addEventListener('mouseup', () => { 
    // Use style to set element color
    a.style.color = 'blue';
  });

您可以在鏈接上設置一個 ID 並使用 css 定位它

#my-id {color: blue}
#my-id:active {color: red}

暫無
暫無

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

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