如何使用 javascript 更改 HTML 中不匹配单词的颜色
How to change color for mismatch words in HTML using javascript
我有一个 span
和一个 input
字段;当我在输入字段中输入该文本时,我想更改 span
中文本的颜色。
以下是我的代码:
我想,如果我输入错误的单词,那么该单词将在 span 中变红
var i=0;
var idx=0;
document.body.onkeydown = function(e){
if(e.keyCode == 32 )
{
highlight();
}
}
function highlight() {
var str= document.getElementById("pera").innerText.split(' ');
var text= str[i];
var wrdl = text.length;
var inputText = document.getElementById("pera");
var innerHTML = inputText.innerText;
var pretext = innerHTML.slice(0, idx);
var postext = innerHTML.slice(idx+text.length);
if ( idx >= 0 && text!="")
{
var highlightedText = pretext;
highlightedText += "<span class='highlight'>";
highlightedText += text;
highlightedText += "</span>";
highlightedText += postext;
document.getElementById("pera").innerHTML=highlightedText;
}
i++;
idx += parseInt(text.length+1);
}
.highlight
{
background-color:yellow;
}
<span id="pera">This paragraph is a value of span</span>
</br>
<input type="text" id ="inp" onfocus="highlight();" />
此代码应以绿色突出显示匹配的部分,并以红色突出显示不匹配的部分。
它的工作原理是找到用户输入的文本第一次出现的索引,并在其周围添加开始和结束的 <span>
标记。
function highlight() {
const text = "This paragraph is a value of span"; //The actual text to compair the value against
var value = document.getElementById("in").value; //The input value
var startingIndex = text.indexOf(value); //The string index where the value begins in the paragraph
if (startingIndex!=-1) { //If the value is within the text
var endingIndex = startingIndex+value.length; //The string index where the value ends is just the length of the value added to the starting index
var highlightedText = text.slice(0,startingIndex); //The text from the beginning to the start of the highlight
highlightedText += "<span style=\"color:green;\">"; //Add the HTML which will cause the highlight
highlightedText += text.slice(startingIndex,endingIndex); //Add the text to highlight
highlightedText += "</span>"; //Add the HTML which will cause the end of the highlight
highlightedText += text.slice(endingIndex); //Add the remaining text
document.getElementById("para").innerHTML = highlightedText; //Set the HTML of the paragraph to be the new, highlighted string that we made.
}
}
<span id="para" style="color:red"><span style="color:green">This paragraph is</span> a value of span</span><br><br>
<input type="text" id="in" value="This paragraph is" oninput="highlight()">
new RegExp()
下面的例子使用regular expressions created from the value
of the <input>
on input
.
Regular expressions are patterns used to match character combinations in strings.
如果 (case sensitive) value
is matched by replace()
, we capture 匹配,并将其包装在 <span>
标签中,其中有一个 CSS 规则规定它们应该是 color: red
.
设置 "g"
(全局)标志后,replace()
作用于每个匹配的字符串,而不是仅作用于第一个(如果省略此标志)。
The replace()
method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.
然后我们设置 <p>
的 innerHTML
of the <p>
to the textContent
,所有匹配的文本都包含在 <span>
中。
The Element.innerHTML
property sets or gets the HTML syntax describing the element's descendants.
...
This property provides a simple way to completely replace the contents of an element.
textContent
returns the concatenation of the textContent
property value of every child node, excluding comments and processing instruction nodes. This is an empty string if the node has no children.
最后我们使用 classList.toggle()
及其可选的第二个参数作为 <input>
的 value
;如果 <input>
有一个 value
,任何未正确输入的内容都将显示为红色,否则将保持后备文本颜色。
When a second argument is present: If the second argument evaluates to true
, add specified class value, and if it evaluates to false
, remove it.
const para = document.querySelector( "p" );
document.querySelector( "input" ).addEventListener( "input", function() {
const input = this.value,
content = para.textContent;
para.innerHTML = input ? content.replace(
new RegExp( "(" + input + ")", "g" ), // search for "input.value"
"<span></span>" // replace with "<span>input.value</span>"
) : content;
para.classList.toggle( "active", input );
}, false );
body {
font-family: sans-serif;
color: #444;
}
p.active {
color: darkred;
}
span {
color: darkgreen;
}
input {
padding: .5em;
vertical-align: .1em;
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<label>Change the color of this text: <input type="text"></label>
这是一种无需使用正则表达式即可完成此任务的简单方法。现在您每次都可以对任何字符串对象只使用 replaceColor 函数。
String.prototype.replaceColor = function(search, replacement, replaceContainer) {
var target = this;
var toReplace = target.split(search).join(replacement);
replaceContainer.html(toReplace);
};
$( document ).ready(function() {
var container = $('#para');
var str = container.text();
$('#in').on('keyup', function() {
var replacement = "<span class='redText'>" + this.value +"</span>";
str.replaceColor(this.value, replacement, container);
});
});
.redText {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="para">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
<input type="text" id="in" value="" placeholder="input text"/>
我有一个 span
和一个 input
字段;当我在输入字段中输入该文本时,我想更改 span
中文本的颜色。
以下是我的代码:
我想,如果我输入错误的单词,那么该单词将在 span 中变红
var i=0;
var idx=0;
document.body.onkeydown = function(e){
if(e.keyCode == 32 )
{
highlight();
}
}
function highlight() {
var str= document.getElementById("pera").innerText.split(' ');
var text= str[i];
var wrdl = text.length;
var inputText = document.getElementById("pera");
var innerHTML = inputText.innerText;
var pretext = innerHTML.slice(0, idx);
var postext = innerHTML.slice(idx+text.length);
if ( idx >= 0 && text!="")
{
var highlightedText = pretext;
highlightedText += "<span class='highlight'>";
highlightedText += text;
highlightedText += "</span>";
highlightedText += postext;
document.getElementById("pera").innerHTML=highlightedText;
}
i++;
idx += parseInt(text.length+1);
}
.highlight
{
background-color:yellow;
}
<span id="pera">This paragraph is a value of span</span>
</br>
<input type="text" id ="inp" onfocus="highlight();" />
此代码应以绿色突出显示匹配的部分,并以红色突出显示不匹配的部分。
它的工作原理是找到用户输入的文本第一次出现的索引,并在其周围添加开始和结束的 <span>
标记。
function highlight() {
const text = "This paragraph is a value of span"; //The actual text to compair the value against
var value = document.getElementById("in").value; //The input value
var startingIndex = text.indexOf(value); //The string index where the value begins in the paragraph
if (startingIndex!=-1) { //If the value is within the text
var endingIndex = startingIndex+value.length; //The string index where the value ends is just the length of the value added to the starting index
var highlightedText = text.slice(0,startingIndex); //The text from the beginning to the start of the highlight
highlightedText += "<span style=\"color:green;\">"; //Add the HTML which will cause the highlight
highlightedText += text.slice(startingIndex,endingIndex); //Add the text to highlight
highlightedText += "</span>"; //Add the HTML which will cause the end of the highlight
highlightedText += text.slice(endingIndex); //Add the remaining text
document.getElementById("para").innerHTML = highlightedText; //Set the HTML of the paragraph to be the new, highlighted string that we made.
}
}
<span id="para" style="color:red"><span style="color:green">This paragraph is</span> a value of span</span><br><br>
<input type="text" id="in" value="This paragraph is" oninput="highlight()">
new RegExp()
下面的例子使用regular expressions created from the value
of the <input>
on input
.
Regular expressions are patterns used to match character combinations in strings.
如果 (case sensitive) value
is matched by replace()
, we capture 匹配,并将其包装在 <span>
标签中,其中有一个 CSS 规则规定它们应该是 color: red
.
设置 "g"
(全局)标志后,replace()
作用于每个匹配的字符串,而不是仅作用于第一个(如果省略此标志)。
The
replace()
method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.
然后我们设置 <p>
的 innerHTML
of the <p>
to the textContent
,所有匹配的文本都包含在 <span>
中。
The
Element.innerHTML
property sets or gets the HTML syntax describing the element's descendants.
...
This property provides a simple way to completely replace the contents of an element.
textContent
returns the concatenation of thetextContent
property value of every child node, excluding comments and processing instruction nodes. This is an empty string if the node has no children.
最后我们使用 classList.toggle()
及其可选的第二个参数作为 <input>
的 value
;如果 <input>
有一个 value
,任何未正确输入的内容都将显示为红色,否则将保持后备文本颜色。
When a second argument is present: If the second argument evaluates to
true
, add specified class value, and if it evaluates tofalse
, remove it.
const para = document.querySelector( "p" );
document.querySelector( "input" ).addEventListener( "input", function() {
const input = this.value,
content = para.textContent;
para.innerHTML = input ? content.replace(
new RegExp( "(" + input + ")", "g" ), // search for "input.value"
"<span></span>" // replace with "<span>input.value</span>"
) : content;
para.classList.toggle( "active", input );
}, false );
body {
font-family: sans-serif;
color: #444;
}
p.active {
color: darkred;
}
span {
color: darkgreen;
}
input {
padding: .5em;
vertical-align: .1em;
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<label>Change the color of this text: <input type="text"></label>
这是一种无需使用正则表达式即可完成此任务的简单方法。现在您每次都可以对任何字符串对象只使用 replaceColor 函数。
String.prototype.replaceColor = function(search, replacement, replaceContainer) {
var target = this;
var toReplace = target.split(search).join(replacement);
replaceContainer.html(toReplace);
};
$( document ).ready(function() {
var container = $('#para');
var str = container.text();
$('#in').on('keyup', function() {
var replacement = "<span class='redText'>" + this.value +"</span>";
str.replaceColor(this.value, replacement, container);
});
});
.redText {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="para">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
<input type="text" id="in" value="" placeholder="input text"/>