自動識別頁面中指向文檔文件的鏈接(.doc、.xls、.pdf 等),添加對應 CSS 類名,以便顯示文件類型圖標、提示或特殊樣式。
// 遍歷所有帶 href 的 a 標簽
$('a[href]').each(function() {
const href = $(this).attr('href');
// 匹配以 .doc .xls .pdf 結尾 (不區分大小寫)
const match = href.match(/\.(doc|xls|pdf)$/i);
if (match) {
// match[1] 是捕獲組:doc/xls/pdf
$(this).addClass(match[1]);
}
});
<style>
/* 基礎圖標樣式 */
a.doc, a.xls, a.pdf {
padding-left: 24px;
background-repeat: no-repeat;
background-position: left center;
background-size: 16px 16px;
}
/* 不同文件類型圖標 */
a.doc { background-image: url(icons/word.png); }
a.xls { background-image: url(icons/excel.png); }
a.pdf { background-image: url(icons/pdf.png); }
/* 悬停提示 */
a[href$=".pdf"]::after {
content: " (PDF)";
font-size: 0.85em;
color: #666;
}
</style>
const FILE_TYPES = {
// 文檔
doc: ['doc', 'docx', 'rtf', 'odt'],
xls: ['xls', 'xlsx', 'csv', 'ods'],
pdf: ['pdf'],
// 圖片
img: ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp'],
// 視頻
video: ['mp4', 'webm', 'ogg', 'mov', 'avi'],
// 音頻
audio: ['mp3', 'wav', 'ogg', 'flac', 'aac'],
// 壓縮包
zip: ['zip', 'rar', '7z', 'tar', 'gz'],
// 代碼
code: ['js', 'ts', 'jsx', 'tsx', 'py', 'java', 'cpp', 'cs', 'php', 'rb', 'go', 'rs'],
// 其他
txt: ['txt', 'md', 'log'],
ppt: ['ppt', 'pptx', 'odp']
};
// 構建反向映射:ext -> className
const EXT_TO_CLASS = {};
Object.entries(FILE_TYPES).forEach(([className, exts]) => {
exts.forEach(ext => EXT_TO_CLASS[ext.toLowerCase()] = className;
});
// 核心函數
function enhanceDocumentLinks(container = document) {
$(container).find('a[href]').each(function() {
const href = $(this).attr('href').trim();
if (!href || href.startsWith('#') || href.startsWith('javascript:')) return;
// 提取路徑部分 (去除查詢參數、錨點)
const path = href.split('?')[0].split('#')[0];
// 獲取副檔名
const ext = path.slice(path.lastIndexOf('.') + 1).toLowerCase();
const className = EXT_TO_CLASS[ext];
if (className) {
$(this).addClass(`file-link file-${className} file-ext-${ext}`);
// 可選:添加 title 提示
if (!this.title) this.title = `文件類型: ${ext.toUpperCase()}`;
}
});
}
// 頁面加載時執行
$(enhanceDocumentLinks);
// 動態添加內容後調用 (如 AJAX 載入)
// enhanceDocumentLinks('#dynamicContent');
// 假設服務端在 data-size 屬性返回字節數
$('a[href][data-size]').each(function() {
const bytes = parseInt($(this).data('size'), 10);
if (isNaN(bytes)) return;
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let size = bytes, unit = 0;
while (size >= 1024 && unit < units.length - 1) {
size /= 1024;
unit++;
}
$(this).append(` (${size.toFixed(1)} ${units[unit]})`);
});
function enhanceLinks(root = document) {
const links = root.querySelectorAll('a[href]');
const extMap = new Map([
...['doc','docx','rtf','odt'].map(e => [e, 'doc']),
...['xls','xlsx','csv','ods'].map(e => [e, 'xls']),
['pdf', 'pdf'],
// ...更多
]);
links.forEach(link => {
const href = link.href; // 完整 URL
try {
const url = new URL(href, location.origin);
const pathname = url.pathname;
const ext = pathname.slice(pathname.lastIndexOf('.') + 1).toLowerCase();
const className = extMap.get(ext);
if (className) {
link.classList.add('file-link', `file-${className}`, `file-ext-${ext}`);
}
} catch (e) {
// 無效 URL 忽略
}
});
}
// 使用
enhanceLinks();
// 動態內容觀察
new MutationObserver(() => enhanceLinks(document)).observe(document.body, {subtree: true, childList: true});
rel="noopener noreferrer" (外部鏈接安全)download 屬性提示瀏覽器下載而非預覽aria-label 或 title 說明文件類型和大小通過正則匹配鏈接副檔名自動添加類名是經典的漸進增強技術。現代實現建議:
URL API 解析鏈接,避免手動字符串切割錯誤MutationObserver 處理動態內容