【问题标题】:How to change color for mismatch words in HTML using javascript如何使用javascript更改HTML中不匹配单词的颜色
【发布时间】:2017-07-21 01:02:27
【问题描述】:

我有一个span 和一个input 字段;当我在输入字段中输入该文本时,我想更改 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();" />

【问题讨论】:

  • 你的 jquery 代码在哪里??
  • @priya_singh 你看到提到 jQuery 了吗?
  • @priya_singh 这可以使用纯 JS 来完成。为什么他需要 jQuery?
  • 欢迎来到 SO,请展示您的尝试。另外,请阅读有关如何提问的帮助部分。
  • @Toastrackenigma ya...但是javascript代码在哪里?他试过什么???

标签: javascript html css highlighting


【解决方案1】:

此代码应以绿色突出显示匹配的部分,并以红色突出显示不匹配的部分。

它的工作原理是查找用户输入的文本第一次出现的索引,并在其周围添加开始和结束&lt;span&gt; 标签。

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()">

【讨论】:

  • 不,我想逐个比较单词,如果单词不相等,则在 span 中更改颜色
  • 好吧,你也没有在你的问题中解释过,现在也在这里。如果单词不等于... what?颜色是如何定义的?我相信这对你来说很有意义,但如果你需要帮助,那么你需要正确地解释它。
  • 我想当打字导师。比较单词,如果然后将它们涂成绿色,否则将其涂成红色,
  • 我明白你现在的目标了!我的代码应该为您做到这一点。如果此答案有效,请不要忘记单击左侧旁边的复选标记:D
【解决方案2】:

这是一种无需使用正则表达式即可完成此任务的简单方法。现在您可以每次只对任何字符串对象使用 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"/>

【讨论】:

  • 1.我想比较与单个字符不同的单词,如果两个单词相等则为绿色,如果不相等则为红色。 2.段落颜色起点为黑色。 3. 与java jQuery、AJEX不同,需要纯javascript代码
  • 没问题,亲爱的 Lakhvir,我可以帮助你,但现在我正在工作,我将编写一个具有你想要的功能的新代码 :)
【解决方案3】:

new RegExp()

以下示例使用从&lt;input&gt; 上的value 创建的regular expressions input

正则表达式是用于匹配字符串中字符组合的模式。

如果 (case sensitive) valuereplace() 匹配,我们将 capture 匹配,并将其包装在 &lt;span&gt; 标记中,其中有一条 CSS 规则规定它们应该是 color: red
设置了"g"(全局)标志后,replace() 作用于每个匹配的字符串,而不是仅在省略该标志时作用于第一个。

replace() 方法返回一个新字符串,其中模式的部分或全部匹配被替换。模式可以是字符串或正则表达式,替换可以是字符串或每次匹配调用的函数。

然后,我们将&lt;p&gt;innerHTML 设置为&lt;p&gt;textContent,所有匹配的文本都包含在&lt;span&gt;s 中。

Element.innerHTML 属性设置或获取描述元素后代的 HTML 语法。
...
此属性提供了一种完全替换元素内容的简单方法。


textContent 返回每​​个子节点的textContent 属性值的串联,不包括 cmets 和处理指令节点。如果节点没有子节点,则这是一个空字符串。

最后,我们使用classList.toggle() 及其可选的第二个参数作为&lt;input&gt;value;如果&lt;input&gt;value,则任何未正确键入的内容都将被涂成红色,否则将保持备用文本颜色。

当存在第二个参数时:如果第二个参数的计算结果为 true,则添加指定的类值,如果计算结果为 false,则将其删除。

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>$1</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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    相关资源
    最近更新 更多