![](/img/trans.png)
[英]How to set script only run one times? Greasemonkey/Tampermonkey
[英]How to change a class CSS with a Greasemonkey/Tampermonkey script?
我正在嘗試設置正文的背景圖像,但僅限於使用類banner_url
。 HTML如下:
<body id="app_body" class="banner_url desktopapp" data-backdrop-limit="1">
基本上,我想強制頁面使用以下CSS代替:
.banner_url {
background: url('http://www.pxleyes.com/images/contests/kiwis/fullsize/sourceimage.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
我試圖使用Greasemonkey這樣做,如果它有任何區別。 有誰知道我怎么能這樣做? 我從以下開始,但運氣不好:
function randomBG(){
document.getElementsByClassName("banner_url").style.backgroundImage="url('http://www.pxleyes.com/images/contests/kiwis/fullsize/sourceimage.jpg')no-repeat center center fixed;";
}
randomBG();
為此,只需使用CSS級聯。 使用GM_addStyle()
將樣式表添加到頁面。
注意:
!important
標志來涵蓋某些潛在的沖突。 @run-at document-start
(或使用Stylus,見下文)來最小化與初始渲染后更改樣式相關的“閃爍”。 一個完整的腳本:
// ==UserScript==
// @name _Override banner_url styles
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant GM_addStyle
// @run-at document-start
// ==/UserScript==
GM_addStyle ( `
.banner_url {
background: url('http://www.pxleyes.com/images/contests/kiwis/fullsize/sourceimage.jpg') no-repeat center center fixed !important;
-webkit-background-size: cover !important;
-moz-background-size: cover !important;
-o-background-size: cover !important;
background-size: cover !important;
}
` );
請注意, 如果您使用Greasemonkey 4 ,它已經破壞了GM_addStyle()
(還有很多其他東西) 。
強烈建議您切換到Tampermonkey或Violentmonkey。
事實上,Greasemonkey的控制開發人員也說了很多 。
與此同時,對於那些堅持GM4的受虐狂來說,這是一個墊片:
function GM_addStyle (cssStr) {
var D = document;
var newNode = D.createElement ('style');
newNode.textContent = cssStr;
var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
targ.appendChild (newNode);
}
另外,對於純CSS操作, 時尚 手寫筆擴展是比Greasemonkey / Tampermonkey更好的選擇。
這樣的事情怎么樣?
document.getElementsByClassName("banner_url")[0] .style.backgroundImage="url('http://www.pxleyes.com/images/contests/kiwis/fullsize/sourceimage.jpg')";
但我必須承認,我不確定這個問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.