Jak wyróżnić tekst za pomocą javascript
Czy ktoś może mi pomóc z funkcją javascript, która może podświetlić tekst na stronie internetowej. Wymaganiem jest-podświetl tylko raz, a nie tak jak podświetl wszystkie wystąpienia tekstu, jak to robimy w przypadku wyszukiwania.
12 answers
Możesz użyć jquery efekt podświetlenia.
Ale jeśli jesteś zainteresowany surowym kodem javascript, spójrz na to, co mam Po prostu skopiuj wklej do HTML, otwórz plik i kliknij "highlight" - powinno to podświetlić słowo "fox". Jeśli chodzi o wydajność, myślę, że przydałoby się to dla małego tekstu i pojedynczego powtórzenia (jak określiłeś)
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;
}
}
.highlight {
background-color: yellow;
}
<button onclick="highlight('fox')">Highlight</button>
<div id="inputText">
The fox went over the fence
</div>
Edycje:
Używanie replace
Widzę, że ta odpowiedź zyskała pewną popularność, Pomyślałem, że mogę to dodać. Możesz również łatwo użyć replace
"the fox jumped over the fence".replace(/fox/,"<span>fox</span>");
Lub dla wielu wystąpień (Nie dotyczy pytania, ale zostało zadane w komentarzach) wystarczy dodać global
do wyrażenia regularnego replace.
"the fox jumped over the other fox".replace(/fox/g,"<span>fox</span>");
Mam nadzieję, że to pomoże intrygującym komentującym.
Zamiana HTML na całą stronę www
Aby zastąpić HTML dla całej strony internetowej, należy odwołać się do innerHTML
w treści dokumentu.
document.body.innerHTML
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-02 12:28:05
Oferowane tutaj rozwiązania są dość złe.
- nie możesz używać wyrażeń regularnych, ponieważ w ten sposób wyszukujesz/podświetlasz w znacznikach html.
- nie możesz używać regex, ponieważ nie działa poprawnie z UTF* (cokolwiek z nie-łacińskimi/angielskimi znakami).
- nie możesz po prostu zrobić innerHTML.zastąp, ponieważ nie działa to, gdy znaki mają specjalną notację HTML, np.
&
dla&,<
dla> dla >,ä
Dla ä,ö
dla öü
dla üß
dla ß, itd.
Co musisz zrobić:
Wykonaj pętlę w dokumencie HTML, Znajdź wszystkie węzły tekstu, uzyskaj textContent
, uzyskaj pozycję podświetlenia tekstu za pomocą indexOf
(z opcjonalnym toLowerCase
, Jeśli wielkość liter jest niewrażliwa), dodaj wszystko przed indexof
jako textNode
, dodaj dopasowany tekst z zakresem podświetlenia i powtórz dla reszty textnode (łańcuch podświetlenia może wystąpić wiele razy w łańcuchu textContent
).
Oto kod do to:
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
};
Wtedy możesz użyć go tak:
function TestTextHighlighting(highlightText)
{
var container = document.getElementById("testDocument");
InstantSearch.highlight(container, highlightText);
}
Oto przykładowy dokument 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>
Przy okazji, jeśli szukasz w bazie danych z LIKE
,
na przykład WHERE textField LIKE CONCAT('%', @query, '%')
[czego nie powinieneś robić, powinieneś użyć fulltext-search lub Lucene], wtedy możesz uciec od każdego znaku za pomocą \ i dodać SQL-escape-statement, że znajdziesz znaki specjalne, które są jak-wyrażenia.
Np.
WHERE textField LIKE CONCAT('%', @query, '%') ESCAPE '\'
I wartość @query nie jest '% completed'
, ale '\%\ \c\o\m\p\l\e\t\e\d'
Poprawiona wersja maszynopisu:
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
Użycie:
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-03 07:52:07
Dlaczego używanie funkcji samorozświetlania jest złym pomysłem
Powodem, dla którego prawdopodobnie złym pomysłem jest rozpoczęcie tworzenia własnej funkcji podświetlania od zera, jest to, że z pewnością napotkasz problemy, które inni już rozwiązali. Wyzwania:
- trzeba by usunąć węzły tekstowe z elementami HTML, aby podświetlić swoje dopasowania bez niszczenia zdarzeń DOM i wywoływania regeneracji DOM w kółko (co byłoby w przypadku np.
innerHTML
) - jeśli chcesz usunąć zaznaczone elementy, musisz usunąć elementy HTML z ich zawartością, a także połączyć dzielone węzły tekstowe do dalszych wyszukiwań. Jest to konieczne, ponieważ każda wtyczka highlighter przeszukuje węzły tekstowe w poszukiwaniu dopasowań i jeśli słowa kluczowe zostaną podzielone na kilka węzłów tekstowych, nie zostaną znalezione.
- będziesz również musiał zbudować testy, aby upewnić się, że wtyczka działa w sytuacjach, o których nie myślałeś. Oraz Mówię o testach między przeglądarkami!
Użyj istniejącej wtyczki
Używając istniejącej, dobrze zaimplementowanej wtyczki, nie musisz się martwić o powyższe rzeczy. Artykuł 10 jQuery text highlighter pluginy on Sitepoint porównuje popularne wtyczki zakreślacza.
Spójrz na Marka.js
- Szukaj słów kluczowych osobno zamiast pełnego terminu
- znaki diakrytyczne mapy (na przykład, jeśli "justo" powinno również pasować do "justò")
- ignoruj dopasowania wewnątrz niestandardowych elements
- Użyj niestandardowego elementu podświetlania
- użyj niestandardowej klasy podświetlania
- niestandardowe synonimy map
- Szukaj również wewnątrz iframes
- receive not found terms
Alternatywnie możesz zobaczyć to skrzypce .
Przykład użycia :
// Highlight "keyword" in the specified context
$(".context").mark("keyword");
// Highlight the custom regular expression in the specified context
$(".context").markRegExp(/Lorem/gmi);
Jest to darmowy i rozwijany open-source na Githubie (project reference ).Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-20 10:16:31
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);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-10 20:01:58
Mam ten sam problem, kilka tekst przychodzi poprzez żądanie xmlhttp. Ten tekst jest sformatowany w html. Muszę podkreślić każde zdarzenie.
str='<img src="brown fox.jpg" title="The brown fox" />'
+'<p>some text containing fox.</p>'
Problem polega na tym, że nie muszę podświetlać tekstu w znacznikach. Na przykład muszę wyróżnić fox:
Teraz mogę go zastąpić:
var word="fox";
word="(\\b"+
word.replace(/([{}()[\]\\.?*+^$|=!:~-])/g, "\\$1")
+ "\\b)";
var r = new RegExp(word,"igm");
str.replace(r,"<span class='hl'>$1</span>")
Aby odpowiedzieć na twoje pytanie: możesz pominąć g w opcjach regexp i tylko pierwsze wystąpienie zostanie zastąpione, ale to nadal jest to we właściwości img src i niszczy tag obrazu:
<img src="brown <span class='hl'>fox</span>.jpg" title="The brown <span
class='hl'>fox</span> />
Tak to rozwiązałem, ale zastanawiałem się, czy nie ma lepszego sposobu, czegoś, co przegapiłem w wyrażeniach regularnych:
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>");
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-19 06:38:55
Prosty przykład maszynopisu
Uwaga: choć w wielu sprawach zgadzam się z @Stefanem, potrzebowałem tylko prostej dopasowania:
module myApp.Search {
'use strict';
export class Utils {
private static regexFlags = 'gi';
private static wrapper = 'mark';
private static wrap(match: string): string {
return '<' + Utils.wrapper + '>' + match + '</' + Utils.wrapper + '>';
}
static highlightSearchTerm(term: string, searchResult: string): string {
let regex = new RegExp(term, Utils.regexFlags);
return searchResult.replace(regex, match => Utils.wrap(match));
}
}
}
A następnie konstruowanie rzeczywistego wyniku:
module myApp.Search {
'use strict';
export class SearchResult {
id: string;
title: string;
constructor(result, term?: string) {
this.id = result.id;
this.title = term ? Utils.highlightSearchTerm(term, result.title) : result.title;
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-30 12:50:14
Oto moje rozwiązanie regexp pure JavaScript:
function highlight(text) {
document.body.innerHTML = document.body.innerHTML.replace(
new RegExp(text + '(?!([^<]+)?<)', 'gi'),
'<b style="background-color:#ff0;font-size:100%">$&</b>'
);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-19 07:04:38
Znalazłem podświetl plugin jest najlepszym dopasowaniem, dzięki niemu możesz podświetlić część treści :
$('li').highlight ('bla');
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-24 22:19:51
Też się zastanawiałem, czy mógłbyś spróbować tego, czego się nauczyłem na tym [4]} poście.
Użyłem:
function highlightSelection() {
var userSelection = window.getSelection();
for(var i = 0; i < userSelection.rangeCount; i++) {
highlightRange(userSelection.getRangeAt(i));
}
}
function highlightRange(range) {
var newNode = document.createElement("span");
newNode.setAttribute(
"style",
"background-color: yellow; display: inline;"
);
range.surroundContents(newNode);
}
<html>
<body contextmenu="mymenu">
<menu type="context" id="mymenu">
<menuitem label="Highlight Yellow" onclick="highlightSelection()" icon="/images/comment_icon.gif"></menuitem>
</menu>
<p>this is text, select and right click to high light me! if you can`t see the option, please use this<button onclick="highlightSelection()">button </button><p>
Możesz też spróbować tutaj: http://henriquedonati.com/projects/Extension/extension.html
Xc
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 10:31:20
Żadne z innych rozwiązań nie pasowało do moich potrzeb, i chociaż rozwiązanie Stefana Steigera działało tak, jak oczekiwałem, uznałem je za zbyt gadatliwe.
Oto moja próba:
/**
* 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']);
.highlight {
background: lightpink;
}
<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>
Zalecałbym również użycie czegoś w rodzaju escape-string-regexp jeśli twoje słowa kluczowe mogą mieć znaki specjalne, które muszą być zapisane w regexach:
const keywordRegex = RegExp(keywords.map(escapeRegexp).join('|')), flags);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-05 15:11:42
Od HTML5 możesz używać znaczników <mark></mark>
do podświetlania tekstu. Możesz użyć javascript, aby zawinąć tekst / słowo kluczowe między tymi znacznikami. Oto mały przykład, jak oznaczyć i odznaczyć tekst.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-05 14:44:04
Używając metody surroundContents () na typie Range . Jej jedynym argumentem jest element, który zawija ten zakres.
function styleSelected() {
bg = document.createElement("span");
bg.style.backgroundColor = "yellow";
window.getSelection().getRangeAt(0).surroundContents(bg);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-10 03:16:09