编写替换背景图像的用户脚本

时间:2012-07-18 11:05:13

标签: javascript background greasemonkey userscripts

这是代码

// ==UserScript==
// @name           Wood Background
// @namespace      http://www.nationstates.net/nation=ellorn
// @description    Changes background to wood finish
// @include       http:*//w11.zetaboards.com/Allied_Republics/*
// ==/UserScript==


function addCss(cssString) {
    var head = document.getElementsByTagName('head')[0];
    return unless head;
    var newCss = document.createElement('style');
    newCss.type = "text/css";
    newCss.innerHTML = cssString;
    head.appendChild(newCss);
}  
addCss (
    '* { background: #00ff00                          url('http://awesomewallpapers.files.wordpress.com/2010/01 /wooden_top.jpg') no-repeat 

fixed center;  }'
);

我正在尝试替换网站的背景:http://awesomewallpapers.files.wordpress.com/2010/01/wooden_top.jpg

2 个答案:

答案 0 :(得分:2)

只需更改样式,请使用the Stylish add-on(几乎每个浏览器都可以使用此变体)。

时尚比Greasemonkey或userscripts更快,更轻,更容易。 userstyles.org有很多预制款式可供选择。

除此之外,请使用内置函数,例如GM_addStyle()

以下脚本适用于Firefox和Chrome,以及其他一些浏览器。 (CSS字符串中存在语法错误):

// ==UserScript==
// @name        Wood Background
// @namespace   http://www.nationstates.net/nation=ellorn
// @description Changes background to wood finish
// @include     http:*//w11.zetaboards.com/Allied_Republics/*
// ==/UserScript==

GM_addStyle (
    "* { background: #00ff00 "
    + "url('http://awesomewallpapers.files.wordpress.com/2010/01/wooden_top.jpg')"
    + " no-repeat fixed center; }"
);

请注意,最好将*替换为body

答案 1 :(得分:0)

您可以定义自己的用户样式表来覆盖网站的作者样式表。我认为这比编写javascript更适合改变CSS。

以下是关于如何实现这一目标的a short introduction

除此之外,如果你正确地移交CSS字符串(固定引用和换行符),你的代码应该可以正常工作:

var css = "* { background: #00ff00 url('http://awesomewallpapers.files.wordpress.com/2010/01/wooden_top.jpg') no-repeat fixed center;  }";

addCss ( css );

但请注意,*将会中断,因为您将木制背景应用于每个元素,而不仅仅是您的背景元素(HTML或正文或包装div)。< / p>