Home >Web Front-end >CSS Tutorial >How to Override Class CSS Using Greasemonkey or Tampermonkey Scripts?

How to Override Class CSS Using Greasemonkey or Tampermonkey Scripts?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 17:00:30570browse

How to Override Class CSS Using Greasemonkey or Tampermonkey Scripts?

How to Alter Class CSS Using Greasemonkey or Tampermonkey Script

You're attempting to modify the background image of the body element specifically when it has the "banner_url" class. While your initial approach with getElementByClassName was not successful, there is a straightforward solution using Greasemonkey or Tampermonkey scripts.

Utilizing CSS Cascade and GM_addStyle

To achieve your desired result, employ the CSS cascade and the GM_addStyle() function to inject a custom CSS rule into the page. By using the !important flag, you can override any potential conflicts. Additionally, using @run-at document-start (or the Stylus extension) minimizes the visual flicker associated with post-render style changes.

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

Note: If you're using Greasemonkey 4, its GM_addStyle() functionality is unreliable. Consider switching to Tampermonkey or Violentmonkey for increased reliability. A compatibility shim is provided for those who insist on using GM4.

Pure CSS Manipulation

For pure CSS manipulation, consider using the Stylus extension. It offers greater flexibility and a dedicated interface for CSS management, making it a more suitable option than Greasemonkey or Tampermonkey in this context.

The above is the detailed content of How to Override Class CSS Using Greasemonkey or Tampermonkey Scripts?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn