簡體   English   中英

Greasemonkey:突出顯示 HTML 文件中的許多單詞

[英]Greasemonkey: Highlight many words in a HTML-File

我想用 Greasemonkey 突出顯示兩個詞,例如“巴塞爾,伯爾尼”。 如果我只使用巴塞爾,下面的版本有效。 不是很好,但足夠好了。 但是當我使用兩個詞時,突出顯示不起作用。

// ==UserScript==
// @name        highlight-some-words
// @description highlight some words in html
// @grant       none
// ==/UserScript==

document.body.innerHTML= document.body.innerHTML.replace(/Basel|Bern/g, function(m){
    return '<span style="background-color:lightgreen">'+m+'</span>'
});

編輯:有趣的是,該腳本適用於 stackoverflow.com 但不適用於 google.com。 為什么? 那么如何修改腳本呢?

正如我在評論中所說,在搜索巴塞爾和伯爾尼后在 google.com 上工作正常(通過控制台)......也許作為 GM 腳本它運行得太早了

@wOxxOm 提出了一個很好的觀點 - 更改 innerHTML 會弄亂頁面中的事件處理程序,更好的方法是僅更改文本節點。 以下可能不是最有效的方法,但它是我多年前寫的一個油脂猴腳本的衍生物,當時油脂猴還不到一年!!

function highlightWord(word) {
    var xpath = "//text()[contains(., '" + word + "')]";
    var texts = document.evaluate(xpath, document.body, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
    for (n = 0; n < texts.snapshotLength; n++) {
        var textNode = texts.snapshotItem(n);
        var p = textNode.parentNode;
        var a = [];
        var frag = document.createDocumentFragment();
        textNode.nodeValue.split(word).forEach(function(text, i) {
            var node;
            if (i) {
                node = document.createElement('span');
                node.style.backgroundColor = 'lightgreen';
                node.appendChild(document.createTextNode(word));
                frag.appendChild(node);
            }
            if (text.length) {
                frag.appendChild(document.createTextNode(text));
            }
            return a;
        });
        p.replaceChild(frag, textNode);
    }
}
highlightWord('Basel');
highlightWord('Bern');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM