【问题标题】:How to change active color of hyperlink with javascript?如何使用 javascript 更改超链接的活动颜色?
【发布时间】:2020-10-06 20:31:25
【问题描述】:

我正在尝试使用 javascript 添加一堆

/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 中应该是红色。其他链接是黑色的,然后在悬停时变为蓝色,在活动时变为红色。我希望新的超链接在活动时变为蓝色并变为红色。

【问题讨论】:

  • 能否分享一下code pen上的sn-ps代码或者提供完整的HTML、CSS、JS代码。
  • 呃,我的 javascript 充满了与服务器数据的交互,所以有点复杂。我只是在检查是否已经存在可以处理这种情况的 javascript 方法,例如 tag.style.color。
  • 试试 document.getElementById("myDIV").classList.add("mystyle"); w3schools.com/jsref/prop_element_classlist.asp 或切换而不是添加
  • 这似乎很有希望,但这仅在单击按钮后才有效,我只希望在它处于活动状态时更改颜色。在完全点击之前。

标签: javascript html css colors


【解决方案1】:

似乎没有编程方式来定位 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';
  });

【讨论】:

    【解决方案2】:

    您可以在链接上设置一个 ID 并使用 css 定位它

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-06
      • 1970-01-01
      相关资源
      最近更新 更多