gpt4 book ai didi

javascript - 更新镜像 div 中的文本后输入为空

转载 作者:行者123 更新时间:2023-12-02 23:53:16 25 4
gpt4 key购买 nike

我正在尝试创建一个非常基本的 Markdown 编辑器。我使用左侧的文本区域来输入数据,在右侧,我有一个入口点 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>

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

最佳答案

一件事:这里

            md.innerHTML = before + newWord;

您正在使用 newWord 来剪切输出。你需要定义一些类似于beforeafter,以及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

关于javascript - 更新镜像 div 中的文本后输入为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55547180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com