You need to enable JavaScript to run this app. 如何在父元素含指定class时修改img src,求可在Tampermonkey使用的代码
优惠活动
大模型
产品
解决方案
定价
更多

如何在父元素含指定class时修改img src,求可在Tampermonkey使用的代码

Tampermonkey 实现未获得奖杯图片替换脚本

完整可直接使用的脚本代码

// ==UserScript==
// @name         PSNProfiles 未获得奖杯替换为隐藏图标
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  将 class 包含 trophy unearned 的 picture 标签内的图片替换为隐藏奖杯图标
// @match        *://*.psnprofiles.com/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    // 替换目标图标地址
    const HIDDEN_TROPHY_SRC = 'https://psnprofiles.com/lib/img/icons/40-hidden.png';

    // 单个元素替换逻辑
    function replaceUnearnedTrophyImg(pictureEl) {
        const imgEl = pictureEl.querySelector('img');
        if (imgEl && imgEl.src !== HIDDEN_TROPHY_SRC) {
            imgEl.src = HIDDEN_TROPHY_SRC;
            // 可选:替换srcset避免响应式规则加载回原图标
            if (imgEl.srcset) imgEl.srcset = HIDDEN_TROPHY_SRC;
        }
    }

    // 页面加载完成后先处理已存在的奖杯元素
    document.addEventListener('DOMContentLoaded', () => {
        document.querySelectorAll('picture.trophy.unearned').forEach(replaceUnearnedTrophyImg);
    });

    // 监听页面动态内容变化,处理滚动/异步加载新增的奖杯元素
    const observer = new MutationObserver((mutations) => {
        mutations.forEach(mutation => {
            mutation.addedNodes.forEach(node => {
                if (node.nodeType === Node.ELEMENT_NODE) {
                    // 新增节点本身就是目标标签的情况
                    if (node.matches('picture.trophy.unearned')) {
                        replaceUnearnedTrophyImg(node);
                    }
                    // 新增节点内部包含目标标签的情况
                    node.querySelectorAll('picture.trophy.unearned').forEach(replaceUnearnedTrophyImg);
                }
            });
        });
    });

    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
})();

使用说明

  • 打开 Tampermonkey 插件,选择「创建新脚本」
  • 删除默认生成的所有内容,粘贴上述代码后保存即可生效
  • 脚本同时兼容静态加载和动态滚动加载的奖杯内容,无需手动刷新触发替换

内容的提问来源于stack exchange,提问作者Sebie8

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 01:42:01