Writing a userscript that replaces a background image

社会主义新天地 提交于 2019-12-02 19:51:17

问题


This is the code

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

I'm trying to replace the background of the site: http://awesomewallpapers.files.wordpress.com/2010/01/wooden_top.jpg


回答1:


For just style changes, use the Stylish add-on (some variant of this is available on almost every browser).

Stylish is faster, lighter, and easier than Greasemonkey or userscripts. There are plenty of pre-made styles available at userstyles.org.

Barring that, use built-in functions, like GM_addStyle().

The following script works on Firefox and Chrome, and probably a few other browsers. (There was a syntax error in the CSS string) :

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

Note that it would be best to replace the * with body.




回答2:


You can define your own user-stylesheet to overwrite the author stylesheets of websites. I think this would be better suited to alter CSS than writing javascript.

Here is a short introduction on how to achieve that.

Besides from that your code should work in general if you hand over the CSS-string correctly (fixed quoting and linebreak):

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

addCss ( css );

Note however, that * will break, since you are applying the wooden background to every element, not only your background-element (HTML or body or a wrapper div).



来源:https://stackoverflow.com/questions/11539871/writing-a-userscript-that-replaces-a-background-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!