简体   繁体   English

如何将textarea值与div中的文本进行比较

[英]How to compare textarea value with text in a div

I am trying to make a simple typewriter in which the user needs to type a given text.我正在尝试制作一个简单的打字机,用户需要在其中输入给定的文本。 This text written by the user will be compared with that given text and if it matches the background color of that given text will turn green.用户编写的此文本将与该给定文本进行比较,如果与该给定文本的背景颜色匹配,则该文本将变为绿色。

I have this div:我有这个 div:

<div class="textToWrite">this is a text</div>

and this text area:和这个文本区域:

<textarea id="textarea-space" rows="10" cols="75" placeholder="type here your text"></textarea>

I have a javascript code with a eventlistener on the textarea:我在 textarea 上有一个带有事件侦听器的 javascript 代码:

textarea1.addEventListener("keypress", checkInputWithText,false);

whenever a key in the textarea is pressed it checks if the text is the same as the value of the textToWrite div:每当按下 textarea 中的一个键时,它会检查文本是否与 textToWrite div 的值相同:

function checkInputWithText(e){
   if(textarea1.readOnly == false){
     let textToWrite = document.querySelector(".textToWrite");
     if(textarea1.value.trim() == textToWrite.textContent.trim()){
       textToWrite.style.backgroundColor = "green";
     }
   }
}

The problem is that the compare does not work.问题是比较不起作用。 Can somebody please explain what I am doing wrong, so please not only give a solution but also an explanation so that I can learn.有人可以解释我做错了什么,所以请不仅提供解决方案,而且还提供解释,以便我可以学习。

 function checkInputWithText(e) { if (textarea1.readOnly == false) { let textToWrite = document.querySelector(".textToWrite"); if (textarea1.value.trim() == textToWrite.textContent.trim()) { textToWrite.style.backgroundColor = "green"; } } }
 <div class="textToWrite">this is a text</div> <textarea id="textarea-space" rows="10" cols="75" placeholder="type here your text"></textarea>

For the complete code please check:有关完整代码,请检查:

JSFiddle JSFiddle

I believe you meant to do this?我相信你是故意这样做的?

 let field; // save the field let textToWrite; // we only want to define it once function checkInputWithText(e) { if (this.value.trim() == textToWrite) { field.style.backgroundColor = "green"; } } window.addEventListener("load", function() { // to make sure the fields exist. field = document.querySelector(".textToWrite"); textToWrite= field.textContent.trim(); document.getElementById("textarea-space").addEventListener("input", checkInputWithText); });
 <div class="textToWrite">this is a text</div> <textarea id="textarea-space" rows="10" cols="75" placeholder="type here your text"></textarea>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM