update code

This commit is contained in:
lychang
2025-11-14 01:21:48 +08:00
parent 00545db202
commit 95652ed5be
4 changed files with 187 additions and 132 deletions

View File

@@ -38,11 +38,57 @@ function markdownToHtml(markdown) {
// 替换图片
html = html.replace(/!\[(.*?)\]\((.*?)\)/g, '<img src="$2" alt="$1" style="max-width: 100%;">');
// 替换表格(简单实现)
html = html.replace(/\|(.+)\|/g, function(match) {
// 替换表格(增强实现)
html = html.replace(/\|(.+)\|\n\|([-|: ]+)\|\n((?:\|.+\|\n)*)/g, function(match, headerRow, separatorRow, bodyRows) {
// 解析表头
const headers = headerRow.split('|').filter(cell => cell.trim());
// 解析分隔行,确定对齐方式
const separators = separatorRow.split('|').filter(cell => cell.trim());
const alignments = separators.map(sep => {
if (sep.startsWith(':') && sep.endsWith(':')) return 'center';
if (sep.endsWith(':')) return 'right';
return 'left';
});
// 构建表头HTML
let tableHtml = '<table style="border-collapse: collapse; width: 100%; margin: 10px 0; border: 1px solid #ddd;">';
tableHtml += '<thead><tr style="background-color: #f5f5f5;">';
headers.forEach((header, index) => {
const alignment = alignments[index] || 'left';
tableHtml += `<th style="border: 1px solid #ddd; padding: 8px; text-align: ${alignment}; font-weight: bold;">${header.trim()}</th>`;
});
tableHtml += '</tr></thead>';
// 解析表格主体
const bodyRowsArray = bodyRows.trim().split('\n');
if (bodyRowsArray.length > 0) {
tableHtml += '<tbody>';
bodyRowsArray.forEach(row => {
const cells = row.split('|').filter(cell => cell.trim());
if (cells.length > 0) {
tableHtml += '<tr>';
cells.forEach((cell, index) => {
const alignment = alignments[index] || 'left';
tableHtml += `<td style="border: 1px solid #ddd; padding: 8px; text-align: ${alignment};">${cell.trim()}</td>`;
});
tableHtml += '</tr>';
}
});
tableHtml += '</tbody>';
}
tableHtml += '</table>';
return tableHtml;
});
// 处理简单的单行表格(向后兼容)
html = html.replace(/^\|(.+)\|$/gm, function(match) {
const cells = match.split('|').filter(cell => cell.trim());
if (cells.length > 0) {
return '<tr><td>' + cells.join('</td><td>') + '</td></tr>';
return '<table style="border-collapse: collapse; width: 100%; margin: 10px 0; border: 1px solid #ddd;"><tr>' +
cells.map(cell => `<td style="border: 1px solid #ddd; padding: 8px;">${cell.trim()}</td>`).join('') +
'</tr></table>';
}
return match;
});