写一段显示新文档与旧文档文本变化的代码
时间: 2023-08-21 12:07:49 浏览: 36
你可以使用第三方库 `diff-match-patch` 来比较文本的差异,并将差异高亮显示。
下面是一个使用 `diff-match-patch` 库的例子:
```html
<!-- 安装 diff-match-patch 库 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/diff-match-patch/20200713/diff_match_patch.js"></script>
<!-- 新旧文本的容器 -->
<div id="oldText"></div>
<div id="newText"></div>
<script>
// 获取旧文本和新文本的容器
const oldText = document.getElementById("oldText");
const newText = document.getElementById("newText");
// 旧文本和新文本
const oldContent = "这是旧文本";
const newContent = "这是新文本";
// 创建 diff_match_patch 实例
const dmp = new diff_match_patch();
// 获取文本差异
const diffs = dmp.diff_main(oldContent, newContent);
// 应用差异到旧文本容器中并高亮显示修改部分
const oldHtml = dmp.diff_prettyHtml(diffs);
oldText.innerHTML = oldHtml;
// 应用差异到新文本容器中并高亮显示修改部分
const patch = dmp.patch_make(oldContent, diffs);
const newContentPatched = dmp.patch_apply(patch, oldContent)[0];
const newHtml = dmp.diff_prettyHtml(dmp.diff_main(newContentPatched, newContent));
newText.innerHTML = newHtml;
</script>
```
上面的代码将会比较旧文本和新文本的差异,并将修改部分高亮显示。其中 `diffs` 变量存储了文本差异,`oldHtml` 和 `newHtml` 变量存储了高亮显示的旧文本和新文本。