我想将一个字母(我们称之为“n”)更改为另一种颜色,比如说黄色。我希望在所有页面上以所有字体和大小完成此操作。
我找到了 this script对于 Greasemonkey,我认为可以对其进行修改以执行我想要的操作。
我尝试用 "<p style="color:#FFB90F">n</p>"
替换字母“n” ,无济于事。它只是被插入到页面中而不被评估为 CSS。
我该怎么做?我希望能够指定字母和颜色列表。
最佳答案
这是一个常见问题,请注意使用 .innerHTML
或 .html()
的答案。这些将破坏页面的 HTML(用无效字符串替换部分标记)和/或页面功能可能需要的孤立事件处理程序。
稳健的解决方案将使用 DOM 技术来仅修改文本节点。
以下完整脚本使用标准的wrapTextWithElement()
函数。
您可以在 this jsFiddle 查看代码的运行情况。 .
// ==UserScript==
// @name Wrapping/Coloring letters in an HTML page
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @grant GM_addStyle
// ==/UserScript==
//-- Use CSS, *not* inline styles to color/style things
GM_addStyle ( " \
span.coloredLetter { \
background: yellow; \
} \
" );
var letI_Wrapper = new wrapTextWithElement ('i', '<span class="coloredLetter">');
letI_Wrapper.wrap (document.body); // Here we wrap everything.
function wrapTextWithElement (targText, elemToWrapWith, bCaseSensitive) {
var self = this;
var bCaseSensitive = bCaseSensitive || false;
self.targRegEx = new RegExp ("(" + targText + ")", bCaseSensitive ? "" : "i");
self.elemToWrapWith = elemToWrapWith;
self.wrap = function (node) {
$(node).contents ().each ( function () {
if (this.nodeType === Node.ELEMENT_NODE) {
self.wrap (this);
}
else if (this.nodeType === Node.TEXT_NODE) {
var ndText = this.nodeValue;
if (self.targRegEx.test (ndText) ) {
var replaceNodes = $.map (
ndText.split (self.targRegEx),
function (phrase) {
if (self.targRegEx.test (phrase) ) {
/* The $(HTML, props) form does not work if the HTML
has attributes
var wrapped = $(self.elemToWrapWith, {text: phrase} );
*/
var wrapped = $(self.elemToWrapWith).text (phrase);
return wrapped.get ();
}
else {
if (phrase == "")
return null;
else
return document.createTextNode (phrase)
}
}
);
$(this).replaceWith (replaceNodes);
}
}
} );
};
}
关于javascript - 如何更改网页上一个特定字母的颜色(换行文字)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14172290/