簡體   English   中英

如何更改頁面中所有用戶個人資料鏈接的顏色?

[英]How to change the color of all user profile links in a page?

我正在嘗試使用用戶腳本更改瀏覽器中每個用戶個人資料鏈接的顏色。 我的代碼:

// ==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 鏈接和答案鏈接的顏色,而不是評論者的鏈接。

沒有錯誤。


如何更改頁面中所有用戶個人資料鏈接的顏色?

嘗試這個:

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

您可以使用“querySelectorAll”制作更復雜的 CSS 選擇器。

用戶評論附加了不同的 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")

通常,您不應該在 2020 年使用.getElementsByClassName().getElementsByTagName() ,尤其是不要在循環中使用。 正如我的另一篇文章所介紹的那樣,這些是一些最早的 DOM 查詢方法,它們返回“實時”節點列表,這可能很昂貴,尤其是與循環結合使用時。 .querySelectorAll()是現代替代方案,是您真正應該使用的。

您只需要正確查詢任何user-details元素的所有<a>后代並遍歷結果,為每個元素添加一個新類(您也應該盡可能避免內聯樣式,因為它們會導致重復代碼,不能很好地擴展,並且很難覆蓋)。 相反,請使用易於添加和刪除的 CSS 類。

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

而且,當然,請確保您在 CSS 中定義了newColor類:

.newColor { color: someColorYouWant; }

暫無
暫無

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

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