大部分网页默认的背景色为白色,个人感觉比较刺眼,于是写了个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上的背景色,脚本的适用范围有限。
相关推荐:
jquery实现点击a链接处显示背景色的方法
css3 渐变背景色使用方法 兼容ie9+
显示背景色网页特效css代码
以上就是js动态修改网页body的背景色实例分享的详细内容。
