如何使用CSS为YouTube中包含特定文本的标题设置专属样式
实现方案
原生CSS目前不支持直接根据标签内文本内容匹配元素,所以需要结合扩展工具实现,两种常用可落地方案如下:
方案1:用户脚本+自定义样式(兼容性最好,推荐)
通过JS匹配对应文本的元素后添加专属类,再用CSS修改样式,适配所有Chrome、Firefox内核浏览器:
- 先安装Tampermonkey、Violentmonkey这类用户脚本管理扩展
- 新建脚本,粘贴如下代码后保存:
// ==UserScript== // @name YouTube特定标题自定义样式 // @match *://*.youtube.com/* // @grant GM_addStyle // ==/UserScript== // 注入自定义样式,颜色值可自行修改 GM_addStyle(` .custom-target-title { color: #ff0000 !important; } `); function matchTargetTitle() { const titleEls = document.querySelectorAll('yt-formatted-string.style-scope.ytd-video-primary-info-renderer'); titleEls.forEach(el => { if(el.textContent.trim() === 'Title here') { el.classList.add('custom-target-title'); } }); } // 适配YouTube单页加载逻辑,监听页面变动触发匹配 const observer = new MutationObserver(matchTargetTitle); observer.observe(document.body, { childList: true, subtree: true }); // 页面首次加载时执行一次匹配 matchTargetTitle();
方案2:Stylus扩展语法实现(兼容性较差)
如果你正在用Stylus做自定义主题,部分版本支持非标准的contains选择器,可以直接写入如下样式代码:
/* 火狐内核兼容写法 */ yt-formatted-string.style-scope.ytd-video-primary-info-renderer:-moz-contains("Title here") { color: #ff0000 !important; } /* Stylus自定义语法兼容写法 */ yt-formatted-string.style-scope.ytd-video-primary-info-renderer:contains("Title here") { color: #ff0000 !important; }
注意:该方案仅在特定浏览器+Stylus版本组合下生效,稳定性不如方案1。
内容的提问来源于stack exchange,提问作者sheep
相关产品推荐
相关产品推荐

