javascript 按下键盘上的空格键后,单词会被着色,我想在最后一个字母后立即着色

nszi6y05  于 12个月前  发布在  Java
关注(0)|答案(2)|浏览(267)

我有一个JavaScript脚本的颜色文本的问题。有字符串设置为着色,但只有当我按键盘上的“空格”键时,单词才会着色。如果我写这个单词,它不会着色。如果我写这个单词并按空格键,它就会着色。
我想在我写单词的时候立即给它上色,而不需要等待按空格键。例如,我设置HELLO应该上色。我想在我按完最后一个O的时候立即上色,而不是在我键入HELLO(有最后一个空格)的时候。
当您尝试在代码面板中手动编写内容时会出现问题,例如,如果您编写Hello。问题在于changeColor()函数,有一个Keyup Event和一个Space Key Pressed
我试着删除了与事件相关的部分代码(“keyup”.和keycode,但一切都中断了,不工作。我是新的JavaScript,我不能解决它。

index.html

<div id="editor" contenteditable="true" oninput="showPreview();" onchange="changeColor();">&lt;h1>This is a Heading&lt;/h1>
    &lt;p>This is a paragraph.&lt;/p>
  </div>
    
    <h3>PREVIEW</h3>
    <div class="preview-area">
      <iframe id="preview-window"></iframe>
    </div>

字符串

style.css

#editor {
  width: 400px;
  height: 100px;
  padding: 10px;
  background-color: #444;
  color: white;
  font-size: 14px;
  font-family: monospace;
  white-space: pre;
}
.statement {
  color: orange;
}

JavaScript.js

function applyColoring(element) {
    var keywords = ["DIV", "DIV", "H1", "H1", "P", "P", "HELLO", "<", ">", "/"];
  
    var newHTML = "";
    // Loop through words
    str = element.innerText;
    (chunks = str
      .split(new RegExp(keywords.map((w) => `(${w})`).join("|"), "i"))
      .filter(Boolean)),
      (markup = chunks.reduce((acc, chunk) => {
        acc += keywords.includes(chunk.toUpperCase())
          ? `<span class="statement">${chunk}</span>`
          : `<span class='other'>${chunk}</span>`;
        return acc;
      }, ""));
    element.innerHTML = markup;
  }
  

  // CHANGE COLOR 
  function changeColor() {
    // Keyup event
    document.querySelector("#editor").addEventListener("keyup", (e) => {
      // Space key pressed
      if (e.keyCode == 32) {
        applyColoring(e.target);
  
        // Set cursor postion to end of text
        //    document.querySelector('#editor').focus()
        var child = e.target.children;
        var range = document.createRange();
        var sel = window.getSelection();
        range.setStart(child[child.length - 1], 1);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
        this.focus();
      }
    });
  }
  
changeColor()
applyColoring(document.getElementById('editor'));

//PREVIEW
function showPreview() {
    var editor = document.getElementById("editor").innerText;
  
    // var cssCode =
    //  "<style>" + document.getElementById("cssCode").value + "</style>";
    // var jsCode =
    //  "<scri" + "pt>" + document.getElementById("jsCode").value + "</scri" + "pt>";
    
    var frame = document.getElementById("preview-window").contentWindow.document;
    document.getElementById("preview-window").srcdoc = editor;
    frame.open();
    //frame.write(htmlCode + cssCode + jsCode);
    frame.write(editor);
    frame.close();
  }
  
  showPreview()

vfwfrxfs

vfwfrxfs1#

在键入最后一个字母后立即为单词着色您可以使用"input"事件而不是依赖于"keyup"事件这将允许您在键入每个字母后立即更新颜色
此外,我还对applyColoring函数进行了一些调整,以便更好地处理。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        #editor {
            width: 400px;
            height: 100px;
            padding: 10px;
            background-color: #444;
            color: white;
            font-size: 14px;
            font-family: monospace;
            white-space: pre;
        }

        .statement {
            color: orange;
        }
    </style>
</head>
<body>

<div id="editor" contenteditable="true" oninput="changeColor(); showPreview();">
    &lt;h1>This is a Heading&lt;/h1>
    &lt;p>This is a paragraph.&lt;/p>
</div>

<h3>PREVIEW</h3>
<div class="preview-area">
    <iframe id="preview-window"></iframe>
</div>

<script>
    function applyColoring(element) {
        var keywords = ["DIV", "H1", "P", "HELLO", "<", ">", "/"];

        var newHTML = "";
        // Loop through words
        str = element.innerText;
        (chunks = str
            .split(new RegExp(keywords.map((w) => `(${w})`).join("|"), "i"))
            .filter(Boolean)),
            (markup = chunks.reduce((acc, chunk) => {
                acc += keywords.includes(chunk.toUpperCase())
                    ? `<span class="statement">${chunk}</span>`
                    : `<span class='other'>${chunk}</span>`;
                return acc;
            }, ""));
        element.innerHTML = markup;
    }

    // CHANGE COLOR
    function changeColor() {
        var editor = document.getElementById("editor");
        applyColoring(editor);

        // Set cursor position to the end of text
        var child = editor.children;
        var range = document.createRange();
        var sel = window.getSelection();
        range.setStart(child[child.length - 1], 1);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
        editor.focus();
    }

   function showPreview() {
    var editorContent = document.getElementById("editor").innerText;
    var frame = document.getElementById("preview-window");
    
   
    // Create a data URL with the HTML content
    var dataURL = "data:text/html;charset=utf-8," + encodeURIComponent(editorContent);
    
    // Set the iframe src attribute to the data URL
    frame.src = dataURL;
}
changeColor()

showPreview()

</script>

</body>
</html>

字符串

t1qtbnec

t1qtbnec2#

您的思路是正确的:您不必删除整个'keyup'事件侦听器代码-只需删除逻辑周围的if语句。if (e.keyCode == 32)检查是否按下了Space键,因此如果您希望在按下 any 键时运行这部分代码,只需不使用if语句即可。

function changeColor() {
    // Keyup event
    document.querySelector("#editor").addEventListener("keyup", (e) => {
      // // Space key pressed
      // if (e.keyCode == 32) {
        applyColoring(e.target);
  
        // Set cursor postion to end of text
        //    document.querySelector('#editor').focus()
        var child = e.target.children;
        var range = document.createRange();
        var sel = window.getSelection();
        range.setStart(child[child.length - 1], 1);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
        this.focus();
      // }
    });
  }

字符串

相关问题