首页 文章

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

提问于
浏览
29

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

<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();

2 回答

  • 3

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

    • 我们使用 !important 标志来涵盖某些潜在的冲突 .

    • 使用 @run-at document-start (或使用手写笔,见下文)以最小化与初始渲染后更改样式相关联的"flicker" .

    A complete script:

    // ==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;
        }
    ` );
    

    注意 if you are using Greasemonkey 4 ,它已经破坏了 GM_addStyle() (以及许多其他东西) .
    这是 strongly recommended that you switch to Tampermonkey or Violentmonkey.
    事实上,Greasemonkey的控制开发人员says as much himself .

    与此同时,对于那些坚持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);
    }
    

    Also, for pure CSS manipulation, the Stylish Stylus extension is a better choice than Greasemonkey/Tampermonkey.

  • 52

    这样的事情怎么样?

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

    但我必须承认,我不确定这个问题

相关问题