简体   繁体   中英

How to change active color of hyperlink with javascript?

I'm trying to add in a bunch of <p<a/a>/p> elements with javascript and wanted to change the active color of a link with javascript. How would I do that? I can't change the color of all hyperlinks with a:active on the css file because I have a set of other links that I want a different color that I'm currently using css to solve.

These are my additions through 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);

I can change the hyperlink's color to blue but then it loses its active color which would've been red to css. The other links are black which then turn blue on hover and red on active. I'd like the new hyperlink to be blue and turn red when active.

Seems like there's no programmatic way to target the CSS :active state in JavaScript. One approach would be to listen for mouseup and mousedown events on the links in question and set their color via style.

  // 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';
  });

You can set an ID on the link and target that with the css

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

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