This article mainly introduces the example code of JS dynamically modifying the background color of the web page body. Friends who need it can refer to it. I hope it can help everyone.
The default background color of most web pages is white, which personally feels dazzling, so I wrote a JS script to change the background color of the body part. The code is as follows:
// ==UserScript== // @name ChangeBackgroundColor // @namespace tingl // @include * // @version 1 // @grant none // ==/UserScript== (function () { 'use strict'; var color = '#ececec'; var style; function createStyle() { style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = 'body {background-color: ' + color + ' !important;}'; } function changeBackgroundColor() { if(!style.parentNode) document.head.appendChild(style); } createStyle(); changeBackgroundColor(); document.head.addEventListener("DOMNodeRemoved",changeBackgroundColor); }) ()
Code It's relatively simple. You directly create a CSS style rule on the body, and then add it to the head. If the web page content changes or asynchronous update causes the style to be removed, it will be re-added to the head through the event listening mechanism.
Since it simply changes the background color on the body, the script has limited scope of application.
Related recommendations:
jquery method to display background color when clicking a link
How to use CSS3 gradient background color Compatible with IE9+
Display background color web page special effects CSS code
The above is the detailed content of Share an example of dynamically modifying the background color of the web page body using JS. For more information, please follow other related articles on the PHP Chinese website!