Ank*_*kit 83 javascript highlighting
有人可以帮助我使用javascript函数,可以突出显示网页上的文本.并且要求是 - 仅突出显示一次,而不是像在搜索的情况下突出显示所有出现的文本.
guy*_*abi 84
您可以使用jquery 高亮效果.
但如果您对原始javascript代码感兴趣,请查看我得到的内容只需将HTML复制粘贴到HTML中,打开文件并单击"突出显示" - 这应突出显示"fox"一词.性能明智我认为这可以用于小文本和单个重复(如您指定的)
function highlight(text) {
var inputText = document.getElementById("inputText");
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text);
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length);
inputText.innerHTML = innerHTML;
}
}Run Code Online (Sandbox Code Playgroud)
.highlight {
background-color: yellow;
}Run Code Online (Sandbox Code Playgroud)
<button onclick="highlight('fox')">Highlight</button>
<div id="inputText">
The fox went over the fence
</div>Run Code Online (Sandbox Code Playgroud)
编辑:
replace我看到这个答案获得了一些人气,我想我可能会加上它.您也可以轻松使用替换
"the fox jumped over the fence".replace(/fox/,"<span>fox</span>");
或者对于多次出现(与问题无关,但在评论中被询问),您只需添加global替换正则表达式.
"the fox jumped over the other fox".replace(/fox/g,"<span>fox</span>");
希望这对有吸引力的评论者有所帮助.
要替换整个网页的HTML,您应该参考innerHTML文档的正文.
document.body.innerHTML
Ste*_*ger 38
这里提供的解决方案非常糟糕.
&对于&,<对于<,>对于,ä对于ä,ö对于ö ü表示ü ß对于ß等.你需要做什么:
遍历HTML文档,找到所有文本节点,得到了textContent,得到的亮点文本与位置indexOf(带有可选的toLowerCase,如果它应该是不区分大小写),追加之前的一切indexof作为textNode,追加匹配的文本与突出显示跨度,并重复其余的textnode(高亮字符串可能会在textContent字符串中多次出现).
这是以下代码:
var InstantSearch = {
"highlight": function (container, highlightText)
{
var internalHighlighter = function (options)
{
var id = {
container: "container",
tokens: "tokens",
all: "all",
token: "token",
className: "className",
sensitiveSearch: "sensitiveSearch"
},
tokens = options[id.tokens],
allClassName = options[id.all][id.className],
allSensitiveSearch = options[id.all][id.sensitiveSearch];
function checkAndReplace(node, tokenArr, classNameAll, sensitiveSearchAll)
{
var nodeVal = node.nodeValue, parentNode = node.parentNode,
i, j, curToken, myToken, myClassName, mySensitiveSearch,
finalClassName, finalSensitiveSearch,
foundIndex, begin, matched, end,
textNode, span, isFirst;
for (i = 0, j = tokenArr.length; i < j; i++)
{
curToken = tokenArr[i];
myToken = curToken[id.token];
myClassName = curToken[id.className];
mySensitiveSearch = curToken[id.sensitiveSearch];
finalClassName = (classNameAll ? myClassName + " " + classNameAll : myClassName);
finalSensitiveSearch = (typeof sensitiveSearchAll !== "undefined" ? sensitiveSearchAll : mySensitiveSearch);
isFirst = true;
while (true)
{
if (finalSensitiveSearch)
foundIndex = nodeVal.indexOf(myToken);
else
foundIndex = nodeVal.toLowerCase().indexOf(myToken.toLowerCase());
if (foundIndex < 0)
{
if (isFirst)
break;
if (nodeVal)
{
textNode = document.createTextNode(nodeVal);
parentNode.insertBefore(textNode, node);
} // End if (nodeVal)
parentNode.removeChild(node);
break;
} // End if (foundIndex < 0)
isFirst = false;
begin = nodeVal.substring(0, foundIndex);
matched = nodeVal.substr(foundIndex, myToken.length);
if (begin)
{
textNode = document.createTextNode(begin);
parentNode.insertBefore(textNode, node);
} // End if (begin)
span = document.createElement("span");
span.className += finalClassName;
span.appendChild(document.createTextNode(matched));
parentNode.insertBefore(span, node);
nodeVal = nodeVal.substring(foundIndex + myToken.length);
} // Whend
} // Next i
}; // End Function checkAndReplace
function iterator(p)
{
if (p === null) return;
var children = Array.prototype.slice.call(p.childNodes), i, cur;
if (children.length)
{
for (i = 0; i < children.length; i++)
{
cur = children[i];
if (cur.nodeType === 3)
{
checkAndReplace(cur, tokens, allClassName, allSensitiveSearch);
}
else if (cur.nodeType === 1)
{
iterator(cur);
}
}
}
}; // End Function iterator
iterator(options[id.container]);
} // End Function highlighter
;
internalHighlighter(
{
container: container
, all:
{
className: "highlighter"
}
, tokens: [
{
token: highlightText
, className: "highlight"
, sensitiveSearch: false
}
]
}
); // End Call internalHighlighter
} // End Function highlight
};
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它:
function TestTextHighlighting(highlightText)
{
var container = document.getElementById("testDocument");
InstantSearch.highlight(container, highlightText);
}
Run Code Online (Sandbox Code Playgroud)
这是一个示例HTML文档
<!DOCTYPE html>
<html>
<head>
<title>Example of Text Highlight</title>
<style type="text/css" media="screen">
.highlight{ background: #D3E18A;}
.light{ background-color: yellow;}
</style>
</head>
<body>
<div id="testDocument">
This is a test
<span> This is another test</span>
äöüÄÖÜäöüÄÖÜ
<span>Test123äöüÄÖÜ</span>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
顺便说一下,如果你在数据库中搜索LIKE,
例如WHERE textField LIKE CONCAT('%', @query, '%')[你不应该这样做,你应该使用全文搜索或Lucene],那么你可以用\来转义每个字符,并添加一个SQL-escape语句,那就是你会发现LIKE表达式的特殊字符.
例如
WHERE textField LIKE CONCAT('%', @query, '%') ESCAPE '\'
Run Code Online (Sandbox Code Playgroud)
和@query的值不是'%completed%',但'%\c\o\m\p\l\e\t\e\d%'
(已测试,适用于SQL-Server和PostgreSQL,以及支持ESCAPE的所有其他RDBMS系统)
修订后的打字稿版本:
namespace SearchTools
{
export interface IToken
{
token: string;
className: string;
sensitiveSearch: boolean;
}
export class InstantSearch
{
protected m_container: Node;
protected m_defaultClassName: string;
protected m_defaultCaseSensitivity: boolean;
protected m_highlightTokens: IToken[];
constructor(container: Node, tokens: IToken[], defaultClassName?: string, defaultCaseSensitivity?: boolean)
{
this.iterator = this.iterator.bind(this);
this.checkAndReplace = this.checkAndReplace.bind(this);
this.highlight = this.highlight.bind(this);
this.highlightNode = this.highlightNode.bind(this);
this.m_container = container;
this.m_defaultClassName = defaultClassName || "highlight";
this.m_defaultCaseSensitivity = defaultCaseSensitivity || false;
this.m_highlightTokens = tokens || [{
token: "test",
className: this.m_defaultClassName,
sensitiveSearch: this.m_defaultCaseSensitivity
}];
}
protected checkAndReplace(node: Node)
{
let nodeVal: string = node.nodeValue;
let parentNode: Node = node.parentNode;
let textNode: Text = null;
for (let i = 0, j = this.m_highlightTokens.length; i < j; i++)
{
let curToken: IToken = this.m_highlightTokens[i];
let textToHighlight: string = curToken.token;
let highlightClassName: string = curToken.className || this.m_defaultClassName;
let caseSensitive: boolean = curToken.sensitiveSearch || this.m_defaultCaseSensitivity;
let isFirst: boolean = true;
while (true)
{
let foundIndex: number = caseSensitive ?
nodeVal.indexOf(textToHighlight)
: nodeVal.toLowerCase().indexOf(textToHighlight.toLowerCase());
if (foundIndex < 0)
{
if (isFirst)
break;
if (nodeVal)
{
textNode = document.createTextNode(nodeVal);
parentNode.insertBefore(textNode, node);
} // End if (nodeVal)
parentNode.removeChild(node);
break;
} // End if (foundIndex < 0)
isFirst = false;
let begin: string = nodeVal.substring(0, foundIndex);
let matched: string = nodeVal.substr(foundIndex, textToHighlight.length);
if (begin)
{
textNode = document.createTextNode(begin);
parentNode.insertBefore(textNode, node);
} // End if (begin)
let span: HTMLSpanElement = document.createElement("span");
if (!span.classList.contains(highlightClassName))
span.classList.add(highlightClassName);
span.appendChild(document.createTextNode(matched));
parentNode.insertBefore(span, node);
nodeVal = nodeVal.substring(foundIndex + textToHighlight.length);
} // Whend
} // Next i
} // End Sub checkAndReplace
protected iterator(p: Node)
{
if (p == null)
return;
let children: Node[] = Array.prototype.slice.call(p.childNodes);
if (children.length)
{
for (let i = 0; i < children.length; i++)
{
let cur: Node = children[i];
// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
if (cur.nodeType === Node.TEXT_NODE)
{
this.checkAndReplace(cur);
}
else if (cur.nodeType === Node.ELEMENT_NODE)
{
this.iterator(cur);
}
} // Next i
} // End if (children.length)
} // End Sub iterator
public highlightNode(n:Node)
{
this.iterator(n);
} // End Sub highlight
public highlight()
{
this.iterator(this.m_container);
} // End Sub highlight
} // End Class InstantSearch
} // End Namespace SearchTools
Run Code Online (Sandbox Code Playgroud)
用法:
let searchText = document.getElementById("txtSearchText");
let searchContainer = document.body; // document.getElementById("someTable");
let highlighter = new SearchTools.InstantSearch(searchContainer, [
{
token: "this is the text to highlight" // searchText.value,
className: "highlight", // this is the individual highlight class
sensitiveSearch: false
}
]);
// highlighter.highlight(); // this would highlight in the entire table
// foreach tr - for each td2
highlighter.highlightNode(td2); // this highlights in the second column of table
Run Code Online (Sandbox Code Playgroud)
dud*_*ude 32
为什么从头开始构建自己的突出显示功能可能是一个坏主意的原因是因为你肯定会遇到其他人已经解决的问题.挑战:
innerHTML)听起来很复杂?如果你想要一些功能,比如忽略突出显示,变音符号映射,同义词映射,iframe内搜索,分离词搜索等一些元素,这就变得越来越复杂.
使用现有的,实现良好的插件时,您不必担心上面提到的东西.Sitepoint上的第10篇jQuery文本荧光笔插件比较了流行的荧光笔插件.
mark.js是一个用纯JavaScript编写的插件,但也可以作为jQuery插件使用.它的开发目的是提供比其他插件更多的机会,可以选择:
或者你可以看到这个小提琴.
用法示例:
// Highlight "keyword" in the specified context
$(".context").mark("keyword");
// Highlight the custom regular expression in the specified context
$(".context").markRegExp(/Lorem/gmi);
Run Code Online (Sandbox Code Playgroud)
它是免费的,并在GitHub上开发了开源(项目参考).
小智 9
function stylizeHighlightedString() {
var text = window.getSelection();
// For diagnostics
var start = text.anchorOffset;
var end = text.focusOffset - text.anchorOffset;
range = window.getSelection().getRangeAt(0);
var selectionContents = range.extractContents();
var span = document.createElement("span");
span.appendChild(selectionContents);
span.style.backgroundColor = "yellow";
span.style.color = "black";
range.insertNode(span);
}
Run Code Online (Sandbox Code Playgroud)
其他解决方案都没有真正满足我的需求,尽管 Stefan Steiger 的解决方案按我的预期工作,但我发现它有点过于冗长。
以下是我的尝试:
/**
* Highlight keywords inside a DOM element
* @param {string} elem Element to search for keywords in
* @param {string[]} keywords Keywords to highlight
* @param {boolean} caseSensitive Differenciate between capital and lowercase letters
* @param {string} cls Class to apply to the highlighted keyword
*/
function highlight(elem, keywords, caseSensitive = false, cls = 'highlight') {
const flags = caseSensitive ? 'gi' : 'g';
// Sort longer matches first to avoid
// highlighting keywords within keywords.
keywords.sort((a, b) => b.length - a.length);
Array.from(elem.childNodes).forEach(child => {
const keywordRegex = RegExp(keywords.join('|'), flags);
if (child.nodeType !== 3) { // not a text node
highlight(child, keywords, caseSensitive, cls);
} else if (keywordRegex.test(child.textContent)) {
const frag = document.createDocumentFragment();
let lastIdx = 0;
child.textContent.replace(keywordRegex, (match, idx) => {
const part = document.createTextNode(child.textContent.slice(lastIdx, idx));
const highlighted = document.createElement('span');
highlighted.textContent = match;
highlighted.classList.add(cls);
frag.appendChild(part);
frag.appendChild(highlighted);
lastIdx = idx + match.length;
});
const end = document.createTextNode(child.textContent.slice(lastIdx));
frag.appendChild(end);
child.parentNode.replaceChild(frag, child);
}
});
}
// Highlight all keywords found in the page
highlight(document.body, ['lorem', 'amet', 'autem']);Run Code Online (Sandbox Code Playgroud)
.highlight {
background: lightpink;
}Run Code Online (Sandbox Code Playgroud)
<p>Hello world lorem ipsum dolor sit amet, consectetur adipisicing elit. Est vel accusantium totam, ipsum delectus et dignissimos mollitia!</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Numquam, corporis.
<small>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium autem voluptas perferendis dolores ducimus velit error voluptatem, qui rerum modi?</small>
</p>Run Code Online (Sandbox Code Playgroud)
如果您的关键字可以包含需要在正则表达式中转义的特殊字符,我还建议使用类似escape-string-regexp 的东西:
const keywordRegex = RegExp(keywords.map(escapeRegexp).join('|')), flags);
Run Code Online (Sandbox Code Playgroud)
这是我的regexp纯JavaScript解决方案:
function highlight(text) {
document.body.innerHTML = document.body.innerHTML.replace(
new RegExp(text + '(?!([^<]+)?<)', 'gi'),
'<b style="background-color:#ff0;font-size:100%">$&</b>'
);
}
Run Code Online (Sandbox Code Playgroud)
快进到 2019 年,Web API 现在原生支持突出显示文本:
const selection = document.getSelection();
selection.setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset);
Run Code Online (Sandbox Code Playgroud)
一切顺利!anchorNode为选择起始节点,focusNode为选择结束节点。并且,如果它们是文本节点,offset则 是各个节点中起始字符和结束字符的索引。这是文档
他们甚至还有现场演示
我有同样的问题,一堆文本通过 xmlhttp 请求进来。此文本为 html 格式。我需要强调每一个事件。
str='<img src="brown fox.jpg" title="The brown fox" />'
+'<p>some text containing fox.</p>'
Run Code Online (Sandbox Code Playgroud)
问题是我不需要突出显示标签中的文本。例如,我需要突出狐狸:
现在我可以将其替换为:
var word="fox";
word="(\\b"+
word.replace(/([{}()[\]\\.?*+^$|=!:~-])/g, "\\$1")
+ "\\b)";
var r = new RegExp(word,"igm");
str.replace(r,"<span class='hl'>$1</span>")
Run Code Online (Sandbox Code Playgroud)
要回答您的问题:您可以在 regexp 选项中省略 g 并且只有第一次出现将被替换,但这仍然是 img src 属性中的那个并破坏图像标签:
<img src="brown <span class='hl'>fox</span>.jpg" title="The brown <span
class='hl'>fox</span> />
Run Code Online (Sandbox Code Playgroud)
这是我解决它的方法,但想知道是否有更好的方法,我在正则表达式中遗漏了一些东西:
str='<img src="brown fox.jpg" title="The brown fox" />'
+'<p>some text containing fox.</p>'
var word="fox";
word="(\\b"+
word.replace(/([{}()[\]\\.?*+^$|=!:~-])/g, "\\$1")
+ "\\b)";
var r = new RegExp(word,"igm");
str.replace(/(>[^<]+<)/igm,function(a){
return a.replace(r,"<span class='hl'>$1</span>");
});
Run Code Online (Sandbox Code Playgroud)
从 HTML5 开始,您可以使用<mark></mark>标签来突出显示文本。您可以使用 javascript 在这些标签之间包装一些文本/关键字。这是一个关于如何标记和取消标记文本的小例子。
如果您还希望在页面加载时突出显示它,则有一种新方法。
只需添加 #:~:text=Highlight%20These
尝试在新选项卡中访问此链接
/sf/ask/2701210501/#:~:text=Highlight%20a%20text
突出显示“突出显示文本”文本。
此外,目前仅支持 Chrome(感谢GitGitBoom)。
| 归档时间: |
|
| 查看次数: |
206308 次 |
| 最近记录: |