如何使用 Greasemonkey/Tampermonkey 脚本更改类 CSS

How to change a class CSS with a Greasemonkey/Tampermonkey script?

本文关键字:CSS 脚本 Tampermonkey 何使用 Greasemonkey      更新时间:2023-09-26

我正在尝试设置正文的背景图像,但仅限于它使用类banner_url的地方。 该网页如下所示:

<body id="app_body" class="banner_url desktopapp" data-backdrop-limit="1">

基本上,我想强制页面使用以下CSS:

.banner_url {
    background: url('http://www.pxleyes.com/images/contests/kiwis/fullsize/sourceimage.jpg') no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

我正在尝试使用 Greasemonkey 来做到这一点,如果它有任何区别的话。 有谁知道我该怎么做? 我从以下内容开始,但运气不佳:

function randomBG(){
    document.getElementsByClassName("banner_url").style.backgroundImage="url('http://www.pxleyes.com/images/contests/kiwis/fullsize/sourceimage.jpg')no-repeat center center fixed;";
} 
randomBG();

为此,只需使用 CSS 级联。 将样式表添加到带有 GM_addStyle() 的页面。
注意:

  • 我们使用!important标志来涵盖某些潜在的冲突。
  • 使用@run-at document-start(或使用触笔,见下文)来最大程度地减少与初始渲染后更改样式相关的"闪烁"。

完整的脚本:

// ==UserScript==
// @name     _Override banner_url styles
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant    GM_addStyle
// @run-at   document-start
// ==/UserScript==
GM_addStyle ( `
    .banner_url {
        background: url('http://www.pxleyes.com/images/contests/kiwis/fullsize/sourceimage.jpg') no-repeat center center fixed !important;
        -webkit-background-size: cover !important;
        -moz-background-size: cover !important;
        -o-background-size: cover !important;
        background-size: cover !important;
    }
` );

请注意,如果您使用的是 Greasemonkey 4,它已经破坏了GM_addStyle()(以及许多其他东西)。
强烈建议您切换到Tampermonkey或Violentmonkey。
事实上,Greasemonkey的控制开发人员自己也这么说。

与此同时,对于那些坚持使用 GM4 的受虐狂来说,这里有一个垫片:

function GM_addStyle (cssStr) {
    var D               = document;
    var newNode         = D.createElement ('style');
    newNode.textContent = cssStr;
    var targ    = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
    targ.appendChild (newNode);
}

此外,对于纯粹的CSS操作,Style Stylus扩展是比Greasemonkey/Tampermonkey更好的选择。

这样的事情呢?

document.getElementsByClassName("banner_url")[0] .style.backgroundImage="url('http://www.pxleyes.com/images/contests/kiwis/fullsize/sourceimage.jpg')";

但我必须承认我不确定是否理解这个问题