<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文件差异对比</title>
<link rel="stylesheet" href="https://unpkg.com/diff2html/bundles/css/diff2html.min.css">
<style>
body {
font-family: Arial, sans-serif;
}
#result {
border: 1px solid #ddd;
padding: 10px;
margin-top: 20px;
overflow: auto;
}
</style>
</head>
<body>
<h1>对比远程文件与本地文本差异</h1>
<div>
<textarea id="localText" rows="10" cols="50" placeholder="输入本地文本..."></textarea>
</div>
<button id="compareBtn">比较</button>
<div id="result"></div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/diff.min.js"></script>
<script src="
https://cdn.jsdelivr.net/npm/[email protected]/bundles/js/diff2html-ui.min.js
"></script>
<script>
document.getElementById('compareBtn').addEventListener('click', function() {
const remoteFileUrl = 'http://idipportal-dev.ied.com/data/8ball_IDIP_20240821_238.xml'; // 替换为目标远程文件的 URL
const localText = document.getElementById('localText').value;
// 使用 Fetch API 获取远程文件内容
fetch(remoteFileUrl)
.then(response => {
if (!response.ok) {
throw new Error('网络错误');
}
return response.text();
})
.then(remoteText => {
// 使用 Diff.js 计算差异
const diff = Diff.diffLines(remoteText,localText);
// 将 diff 转换为 Diff2Html 所需的格式
let addedCount = 0;
let removedCount = 0;
const ttdiffString = diff.map(part => {
const prefix = part.added ? '+' : part.removed ? '-' : ' ';
// 更新计数器
if (part.added) {
addedCount += part.count || part.value.split('\n').length; // 计算添加的行数
}
if (part.removed) {
removedCount += part.count || part.value.split('\n').length; // 计算删除的行数
}
return part.value.split('\n').map(line => `${prefix}${line}`).join('\n');
}).join('\n');
const diffString = `diff --git a/8ball_IDIP_20240821_238.xml b/8ball_IDIP_20240821_238.xml
index 0000001..0ddf2ba
--- a/8ball_IDIP_20240821_238.xml
+++ b/8ball_IDIP_20240821_238.xml
@@ -${removedCount} +${addedCount} @@
${ttdiffString}
`;
var targetElement = document.getElementById('result');
var configuration = {
drawFileList: false,
fileListToggle: false,
fileListStartVisible: false,
fileContentToggle: false,
matching: 'lines',
outputFormat: 'side-by-side',
synchronisedScroll: true,
highlight: true,
renderNothingWhenEmpty: false,
};
var diff2htmlUi = new Diff2HtmlUI(targetElement, diffString, configuration);
diff2htmlUi.draw();
diff2htmlUi.highlightCode();
})
.catch(error => {
console.error('获取远程文件失败:', error);
document.getElementById('result').innerText = '错误: ' + error.message;
});
});
</script>
</body>
</html>
标签:xml,const,IDIP,diff2html,part,ui,diff,8ball,js
From: https://www.cnblogs.com/kaikaiya/p/18374182