Home > Web Front-end > JS Tutorial > body text

Share an example of dynamically modifying the background color of the web page body using JS

小云云
Release: 2018-01-27 13:23:00
Original
2727 people have browsed it

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);
}) ()
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template