【问题标题】:How to change the color of all user profile links in a page?如何更改页面中所有用户个人资料链接的颜色?
【发布时间】:2020-11-20 18:07:26
【问题描述】:

我正在尝试使用用户脚本更改浏览器中每个用户的个人资料链接的颜色。我的代码:

// ==UserScript==
// @name         Color changer
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  none
// @author       You
// @match        https://puzzling.stackexchange.com/questions/*
// @grant        none
// ==/UserScript==

let users = document.getElementsByClassName("user-details");

for (let user of users) {
    user.getElementsByTagName("a")[0].style.color = "red";
}

由于某种原因,

  • 对于某些帖子,这只会更改每个问题页面中 OP 链接的颜色,而不是评论者和回答者的链接。

错误:

ERROR: Execution of script 'New Userscript' failed! user.getElementsByTagName(...)[0] is undefined
  • 对于某些帖子,这根本不起作用。

错误:

ERROR: Execution of script 'New Userscript' failed! user.getElementsByTagName(...)[0] is undefined
  • 对于某些帖子,这只会更改每个问题页面中 OP 链接和答案链接的颜色,而不是评论者的链接。

没有错误。


如何更改页面中所有用户个人资料链接的颜色?

【问题讨论】:

标签: javascript colors userscripts


【解决方案1】:

试试这个:

document.querySelectorAll('.user-details a').forEach( item => item.style.color = "red")

您可以使用“querySelectorAll”制作更复杂的 CSS 选择器。

用户 cmets 附加了一个不同的 CSS 类,因此您需要:

document.querySelectorAll('.comment-user').forEach( item => item.style.color = "red")

或者...如果你想同时做,你可以尝试用逗号分隔多个 CSS 查询:

document.querySelectorAll('.user-details a, .comment-user').forEach( item => item.style.color = "red")

【讨论】:

    【解决方案2】:

    Generally, you should NOT be using .getElementsByClassName() or .getElementsByTagName() in 2020 and especially not in a loop. 在我的另一篇文章中,这些是一些最早的 DOM 查询方法,它们返回“实时”节点列表,这可能代价高昂,尤其是与循环结合使用时。 .querySelectorAll() 是现代替代品,是您真正应该使用的。

    您只需要正确查询任何<a> 元素的所有<a> 后代并遍历结果,为每个元素添加一个新类(您还应该尽可能避免使用内联样式)导致代码重复,不能很好地扩展,并且难以覆盖)。相反,请使用易于添加和删除的 CSS 类。

    document.querySelector(".user-details a").forEach(function(item){
      item.classList.add("newColor");
    });
    

    当然,请确保您在 CSS 中定义了 newColor 类:

    .newColor { color: someColorYouWant; }
    

    【讨论】:

    • 谢谢!但这给了我forEach is not a function error。我尝试将forEach 替换为forEach.call,但又出现了另一个错误。
    • 只有在 .forEach() 之前的旧浏览器(如 IE)中进行测试时,才会发生这种情况。您可以通过设置Array.protype.slice.call(document.querySelector(".user-details a")).forEach(function(item){ item.classList.add("newColor"); 来修复它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 2012-08-23
    • 2015-11-08
    • 2014-05-10
    • 2022-01-15
    • 1970-01-01
    相关资源
    最近更新 更多