【html】对比两文本的行差异,行内容不相同时使用不同颜色区分

78 阅读1分钟

说明

类似git的diff功能,不过这里是使用div让两个文本框并排,然后逐行对比两个文本框的行差异,行内容不相同的,则使用不同的颜色进行区分。

代码实现

<dependency>
    <groupId>org.github.evenjn</groupId>
    <artifactId>diff</artifactId>
    <version>1.0.0</version>
</dependency>

<dependency>
    <groupId>io.github.java-diff-utils</groupId>
    <artifactId>java-diff-utils</artifactId>
    <version>4.15</version>
</dependency>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>逐行diff文本</title>
    <style>
        .text-box {
            width: 400px;
            height: 200px;
            border: 1px solid #ccc;
            margin-bottom: 10px;
            overflow-y: scroll;
            white-space: pre-wrap; /* 保留换行符 */
            font-family: monospace; /* 使用等宽字体 */
        }

        .match {
            background-color: inherit;
        }

        .added {
            background-color: lightgreen;
        }

        .removed {
            background-color: lightpink;
        }

        .line {
            padding-left: 4px;
        }
    </style>
</head>
<body>

<h1>逐行文本对比</h1>
<div contenteditable="true" class="text-box" id="text1" style="float: left;">文本1(可替换成展示后端接口传入的字段值)</div>
<div contenteditable="true" class="text-box" id="text2">文本2(可替换成展示后端接口传入的字段值)</div>
<button onclick="compareTexts()">信息对比</button>

<script>
    function compareTexts() {
        const text1 = document.getElementById('text1').innerText.split('\n');
        const text2 = document.getElementById('text2').innerText.split('\n');
        const maxLength = Math.max(text1.length, text2.length);

        const result1 = [];
        const result2 = [];

        for (let i = 0; i < maxLength; i++) {
            const line1 = text1[i] || ''; // If line doesn't exist, treat as empty
            const line2 = text2[i] || ''; // If line doesn't exist, treat as empty

            if (line1 === line2) {
                result1.push(`<div class='line match'>${line1}</div>`);
                result2.push(`<div class='line match'>${line2}</div>`);
            } else {
                result1.push(`<div class='line removed'>${line1}</div>`);
                result2.push(`<div class='line added'>${line2}</div>`);
            }
        }

        document.getElementById('text1').innerHTML = result1.join('');
        document.getElementById('text2').innerHTML = result2.join('');
    }
</script>

</body>
</html>

展示效果

image.png