首页 > 解决方案 > 更新镜像 div 中的文本后,输入为空白

问题描述

我正在尝试创建一个非常基本的降价编辑器。我在左侧使用 textarea 输入数据,在右侧,我有一个入口点 div,我在其中存储我输入的所有内容,因为我使用“keyup”侦听器输入它。当代码在单词的开头和结尾使用 * 格式化时,我已经获得了应用类的文本以使其变为粗体,但是在使用此更新 DOM 之后,我尝试输入的下一个单词不会被添加当我通过调试器运行它时,它实际上显示为空白。

这是我目前拥有的JS...

const html = document.querySelector('#html-area');
const md = document.querySelector('#markdown-area');

html.addEventListener("keyup", function(e) {
    md.innerHTML = e.target.value;
    const words = md.innerHTML.split(' ');
    const len = words.length;

    for(let i = 0; i < len; i++) {
        // if the first character is * and the last character is * and the length of the current word is greater than or equal to 2 then change that word by adding the ".bold" class to it. 
        if(words[i][0] === "*" && words[i][words[i].length - 1] === "*" && words[i].length >= 2){

            const indexOfWord = md.innerHTML.split(' ').indexOf(words[i]);

            const newWord = md.innerHTML.split(' ')[indexOfWord] = ` <span class="bold">${md.innerHTML.split(' ')[indexOfWord]}</span> `;

            const before = md.innerHTML.split(' ').slice(0, indexOfWord).join();

            md.innerHTML = before + newWord;

            break;
        }
    }
});

这是我的 HTML ......

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="./css/index.css" />
    <title>MarkDown</title>
  </head>
  <body>
    <!-- HTML -->
    <div id="app">
      <div id="html-container">
        <h2>HTML</h2>
        <section>
          <label for="html-area"></label>
          <textarea
            name="html-area"
            placeholder="type html here..."
            id="html-area"
          ></textarea>
        </section>
      </div>
      <!-- Markdown -->
      <section id="markdown-container">
        <h2>MarkDown</h2>
        <div>
          <div
            id="markdown-area"
          >Markdown text will show here...</div>
        </div>
      </section>
    </div>
    <script src="./index.js"></script>
  </body>
</html>

感谢您提供任何提示或帮助。

标签: javascriptdom

解决方案


一件事:这里

            md.innerHTML = before + newWord;

您正在使用 newWord 削减输出。您需要定义一些after类似于before, 和md.innerHTML = before + newWord + after;.

虽然更好的解决方案是:拆分 - 映射 - 加入。将输入文本拆分为单词,将它们映射为原始版本或粗体版本,然后再加入。像这样的东西:

const html = document.querySelector("#html-area");
const md = document.querySelector("#markdown-area");

const bold = word =>
  `<span class="bold">${word.substring(1, word.length - 1)}</span>`;

const boldOrNot = word =>
  word.startsWith("*") && word.endsWith("*") && word.length > 2
    ? bold(word)
    : word;

html.addEventListener("keyup", function(e) {
  const input = e.target.value;
  const output = input.split(" ").map(boldOrNot).join(" ");
  md.innerHTML = output;
});

https://codepen.io/anon/pen/jRrxZx


推荐阅读