覆盖页面样式
Ain't It Cool News 是一家致力于娱乐新闻报道方面的站点。我很喜欢这个站点。但是,我对网站的外观不太满意,每个新闻标题字体都太粗大了,而且在鼠标移过时还会改变颜色。所以,我写了一个用户脚本来改变我不喜欢的样式。
例 5.3.
aintitreadable.user.js
// ==UserScript==
// @name Ain't It Readable
// @namespace http://diveintogreasemonkey.org/download/
// @description change style on aint-it-cool-news.com
// @include http://aint-it-cool-news.com/*
// @include http://*.aint-it-cool-news.com/*
// ==/UserScript==
function addGlobalStyle(css) {
var head, style;
head = document.getElementsByTagName('head')[0];
if (!head) { return; }
style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = css;
head.appendChild(style);
}
addGlobalStyle(
'h1, h2, h3, h4 {' +
' font-size: 12px ! important;' +
' line-height: 14px ! important;' +
' font-weight: normal ! important;' +
'}' +
'h1:hover, h2:hover, h3:hover, h4:hover {' +
' background-color: inherit ! important;' +
' color: inherit ! important;' +
'}');这个用户脚本十分简单。首先,我定义了一个函数,可以把任意 CSS 添到页面中。有关此函数的信息,请阅读添加 CSS 样式。
function addGlobalStyle(css) {
var head, style;
head = document.getElementsByTagName('head')[0];
if (!head) { return; }
style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = css;
head.appendChild(style);
}接着,我调用这个函数来把 CSS 加到页面中:把标题变小一点,不那么粗,并且取消了当鼠标移过时颜色的变化。在这个案例里,页面对其中每一点都定义了样式规则,所以我用 ! important 关键字,以保证我的样式规则能替换掉页面原有的规则。
注释:这个函数只有一个参数:包含新增的样式规则的字符串。我把字符串排成容易阅读的格式,但是它仍然只是个字符串。
addGlobalStyle(
'h1, h2, h3, h4 {' +
' font-size: 12px ! important;' +
' line-height: 14px ! important;' +
' font-weight: normal ! important;' +
'}' +
'h1:hover, h2:hover, h3:hover, h4:hover {' +
' background-color: inherit ! important;' +
' color: inherit ! important;' +
'}');