簡體   English   中英

使用 JavaScript、HTML 和 CSS 突出顯示單詞

[英]Highlighting a word using JavaScript, HTML, and CSS

我一直在嘗試制作一個打字測試網站,並且幾乎完成了。 我需要做的最后一件事是突出顯示用戶正在輸入的單詞。 例如:如果報價是“hello world”並且用戶正在打招呼; 你好應該突出顯示。 我在網上真的找不到任何東西。 代碼如下:

 var input = document.getElementById("boch"); input.addEventListener("keyup", function(event) { if (event.keyCode === 32) { event.preventDefault(); document.getElementById("bocho").click(); } });
 div { text-align: center; } body { text-align: center; } input[type=text] { width: 100%; padding: 1%; background-color: rgb(255, 255, 255); border-radius: 10px; } h1 { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; } div { height: 10em; position: relative } html { margin: 0; position: absolute; top: 50%; left: 50%; right: 50%; margin-right: -50%; transform: translate(-50%, -50%) } body { background: linear-gradient(-20deg, #e73c7e, #23a6d5, #23d5ab); background-size: 1000000% 1000000%; } button { margin-left: auto; margin-right: auto; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); width: 100px }
 <.DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>repl.it</title> </head> <h1> bocho is cool </h1> </div> <div id="typing-area"> <input type="text" id="boch"> <button id="bocho" onclick="document.getElementById('boch').value = ''">Enter</button> </html>

我將只使用“Bocho 很酷”這句話,所以應該突出顯示。

我創建了一個帶有沙盒的新版本供您使用。 這個版本應該可以正常工作

您可以單擊下面的“運行代碼片段”進行測試

 var element = document.querySelector("#boch"); element.onkeyup = function() { var value = element.value; if(value.includes("bocho")) { document.getElementById('word-1').style.backgroundColor = 'green'; } else { document.getElementById('word-1').style.backgroundColor = 'white'; } if(value.includes("bocho is")) { document.getElementById('word-2').style.backgroundColor = 'green'; } else { document.getElementById('word-2').style.backgroundColor = 'white'; } if(value.includes("bocho is cool")) { document.getElementById('word-3').style.backgroundColor = 'green'; } else { document.getElementById('word-3').style.backgroundColor = 'white'; } }
 <h1> <span id="word-1">bocho</span> <span id="word-2">is</span> <span id="word-3">cool</span> </h1> <input type="text" id="boch">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM