changshanfeilong

大部分网页默认的背景色为白色,个人感觉比较刺眼,于是写了个JS的脚本去改变body部分的背景色,代码如下:

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

代码比较简单,直接创建了一个body上的css样式规则,然后添加到head里,如果网页内容变化或者异步更新等使样式被移除时,通过事件监听机制重新添加到head上。

由于只是简单地改变了body上的背景色,脚本的适用范围有限。

分类:

技术点:

相关文章:

  • 2021-10-06
  • 2021-11-21
  • 2021-05-17
  • 2021-07-21
  • 2022-12-23
  • 2022-12-23
  • 2022-01-01
  • 2021-10-16
猜你喜欢
  • 2021-12-01
  • 2021-06-26
  • 2022-12-23
  • 2022-12-23
  • 2022-01-18
  • 2021-10-20
相关资源
相似解决方案