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

Xeo*_*Xeo 43 javascript css greasemonkey userscripts tampermonkey

我正在尝试设置正文的背景图像,但仅限于使用该类的位置banner_url.HTML如下:

<body id="app_body" class="banner_url desktopapp" data-backdrop-limit="1">
Run Code Online (Sandbox Code Playgroud)

基本上,我想强制页面使用以下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;
}
Run Code Online (Sandbox Code Playgroud)

我试图使用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();
Run Code Online (Sandbox Code Playgroud)

Bro*_*ams 72

为此,只需使用CSS级联.使用样式表添加样式表GM_addStyle().
注意:

  • 我们使用该!important标志来涵盖某些潜在的冲突.
  • 使用@run-at document-start (或使用Stylus,见下文)以最小化与初始渲染后更改样式相关的"闪烁".

一个完整的脚本:

// ==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;
    }
` );
Run Code Online (Sandbox Code Playgroud)

请注意,如果您使用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);
}
Run Code Online (Sandbox Code Playgroud)

另外,对于纯CSS操作, 时尚 手写笔扩展是比Greasemonkey/Tampermonkey更好的选择.

  • 请注意,您必须将`// @grant GM_addStyle`添加到文件的顶部! (14认同)

Lau*_* S. 5

像这样的事情怎么样?

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

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