Home >Web Front-end >CSS Tutorial >How to Overwrite a Class CSS with Greasemonkey/Tampermonkey?
How to Overwrite a Class CSS with Greasemonkey/Tampermonkey
In this scenario, the goal is to modify the background image of the body element, specifically when it contains the class "banner_url," using Greasemonkey or Tampermonkey scripts. Here's how to achieve this:
Using CSS Cascade
Instead of directly modifying the element's style, you can use the CSS cascade to overwrite the existing CSS rules. To do this, add a style sheet to the page using GM_addStyle().
// ==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; } `);
In this script, the "document-start" metadata has been added to minimize the "flickering" that may occur if the style is changed after initial rendering.
Alternative Approach with Greasemonkey 4
If you are using Greasemonkey 4, which has removed GM_addStyle(), you can use the following shim to overcome this issue:
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); }
Pure CSS Manipulation with Stylus
Apart from Greasemonkey and Tampermonkey, you can also consider using the Stylus extension, which provides better options for pure CSS manipulation. This allows you to modify CSS rules directly, making it a more appropriate choice for this specific task.
The above is the detailed content of How to Overwrite a Class CSS with Greasemonkey/Tampermonkey?. For more information, please follow other related articles on the PHP Chinese website!