【问题标题】:Replace line in css file, using Greasemonkey [duplicate]使用Greasemonkey替换css文件中的行[重复]
【发布时间】:2017-12-08 11:51:46
【问题描述】:

我正在尝试编写一个 Greasemonkey 脚本来替换 .css 文件的一行。

all.css的原行是

#header {
    background: transparent url('img/bg-graph-top.png?v=7e4ce14d05fb') no-repeat 50% -25px;
} 

我想用

替换它
#header {
    background: transparent url('https://upload.wikimedia.org/wikipedia/commons/0/09/Dummy_flag.png') no-repeat 50% -25px;
} 

基于https://stackoverflow.com/a/6854437/9072294,我尝试像这样编写我的第一个用户脚本:

// ==UserScript==
// @name            swap
// @include         http://tex.stackexchange.com/*
// @include         https://tex.stackexchange.com/*
// @require         http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==

var desiredImage    = "https://upload.wikimedia.org/wikipedia/commons/0/09/Dummy_flag.png";

//--- Straight image swap:
$('img/bg-graph-top.png?v=7e4ce14d05fb').attr ('src', desiredImage);

/*--- Replace the link's -- with the logo as a background -- contents with just a plain image.
    Since this image is transparent, clear the old BG image.
    Also constrain the new img to its container. 
*/
$('#header all').css ('background-', 'none')
                .append ('<url>').find ('img/bg-graph-top.png?v=7e4ce14d05fb')  .attr ('src', desiredImage).css ();

但是图像没有改变:(

【问题讨论】:

    标签: css greasemonkey userscripts tampermonkey


    【解决方案1】:

    您正在尝试更改背景图像,而不是 &lt;img&gt; 标记,就像其他答案一样。

    对于这样的事情,只需使用 CSS 覆盖。

    这是 Greasemonkey/Tampermonkey 脚本中的样子:

    // ==UserScript==
    // @name        _TeX SE, Swap header background
    // @match       *://tex.stackexchange.com/*
    // @grant       GM_addStyle
    // @run-at      document-start
    // ==/UserScript==
    
    GM_addStyle ( `
        #header {
            background: transparent url('https://upload.wikimedia.org/wikipedia/commons/0/09/Dummy_flag.png') no-repeat 50% -25px !important;
        }
    ` );
    

    注意!important 标志。

    此外,如果您的脚本对 DOM 进行任何操作,@run-at document-start 可能会使事情复杂化。

    无论如何,对于纯粹的 CSS 更改,比如这个,你最好使用the Stylish extension它不那么大惊小怪,性能更好

    【讨论】:

    • 完美答案!非常感谢! (我还不能投票,我会在声望达到 15 时投票)
    • 感谢您对stylish 扩展的建议。你是绝对正确的,这将更容易使用。但是,我真的很高兴您提供了 Greasemonkey 解决方案,因为无论如何安装此扩展程序是为了各种其他目的。
    • 那些偶然发现的人:小心,时尚的扩展现在似乎带有男性软件! addons.mozilla.org/en-US/firefox/addon/stylish
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-21
    • 2020-07-21
    • 1970-01-01
    • 2014-06-28
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    相关资源
    最近更新 更多