【前端】纯JS实现文本对比高亮显示

1.参考demo

1-1、连接:http://incaseofstairs.com/jsdiff/
1-2、例子:

2.页面

<!DOCTYPE html>
<!-- saved from url=(0033)http://incaseofstairs.com/jsdiff/ -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

	<title>Diff Chars</title>
	<link rel="stylesheet" href="./Diff Chars_files/style.css">
</head>
<body>

<div id="settings">
	<h1>Diff</h1>
	<label><input type="radio" name="diff_type" value="diffChars" checked=""> Chars</label>
	<label><input type="radio" name="diff_type" value="diffWords"> Words</label>
	<label><input type="radio" name="diff_type" value="diffLines"> Lines</label>
</div>

<a href="https://github.com/kpdecker/jsdiff" class="source">github.com/kpdecker/jsdiff</a>

<table>
	<tbody><tr>
		<td contenteditable="true" id="a">aurass</td>
		<td contenteditable="true" id="b">aura</td>
		<td><pre id="result">aura<del>ss</del></pre></td>
	</tr>
</tbody></table>

<!--<script src="./Diff Chars_files/diff.js.下载"></script>-->
<script src="diff.js"></script>
<script defer="">
var a = document.getElementById('a');
var b = document.getElementById('b');
var result = document.getElementById('result');

function changed() {
	var diff = Diff[window.diffType](a.textContent, b.textContent);
	var fragment = document.createDocumentFragment();
	for (var i=0; i < diff.length; i++) {

		if (diff[i].added && diff[i + 1] && diff[i + 1].removed) {
			var swap = diff[i];
			diff[i] = diff[i + 1];
			diff[i + 1] = swap;
		}

		var node;
		if (diff[i].removed) {
			node = document.createElement('del');
			node.appendChild(document.createTextNode(diff[i].value));
		} else if (diff[i].added) {
			node = document.createElement('ins');
			node.appendChild(document.createTextNode(diff[i].value));
		} else {
			node = document.createTextNode(diff[i].value);
		}
		fragment.appendChild(node);
	}

	result.textContent = '';
	result.appendChild(fragment);
}

window.onload = function() {
	onDiffTypeChange(document.querySelector('#settings [name="diff_type"]:checked'));
	changed();
};

a.onpaste = a.onchange =
b.onpaste = b.onchange = changed;

if ('oninput' in a) {
	a.oninput = b.oninput = changed;
} else {
	a.onkeyup = b.onkeyup = changed;
}

function onDiffTypeChange(radio) {
	window.diffType = radio.value;
	document.title = "Diff " + radio.value.slice(4);
}

var radio = document.getElementsByName('diff_type');
for (var i = 0; i < radio.length; i++) {
	radio[i].onchange = function(e) {
		onDiffTypeChange(e.target);
		changed();
	}
}
</script>


</body></html>

js:
链接: https://pan.baidu.com/s/1W3tz1acNggIabNXCyKn1hQ 提取码: 8td1 复制这段内容后打开百度网盘手机App,操作更方便哦

posted @ 2024-04-23 16:21  你会很厉害的  阅读(588)  评论(0编辑  收藏  举报
//雪花飘落效果