



// 簡單的偽代碼示例 document.getElementById('mytable').addEventListener('mouseover', function(e) { const targetCell = e.target.closest('td[data-tooltip]'); if (targetCell) { // 清除之前的定時器,防止快速移動鼠標時出現問題 clearTimeout(this.tooltipTimeout); this.tooltipTimeout = setTimeout(() => { let tooltip = document.getElementById('myTooltip'); if (!tooltip) { tooltip = document.createElement('div'); tooltip.id = 'myTooltip'; tooltip.classList.add('tooltip-style'); // 預設css樣式 document.body.appendChild(tooltip); } tooltip.textContent = targetCell.dataset.tooltip; // 根據targetCell的位置計算tooltip的位置 const rect = targetCell.getBoundingClientRect(); tooltip.style.left = `${rect.left + window.scrollX}px`; tooltip.style.top = `${rect.bottom + window.scrollY + 5}px`; // 稍微偏下 tooltip.style.display = 'block'; tooltip.style.opacity = '1'; }, 200); // 200ms 延遲顯示 } }); document.getElementById('myTable').addEventListener('mouseout', function(e) { // 鼠標移出時立即隱藏,或者也加個小延遲 clearTimeout(this.tooltipTimeout); const tooltip = document.getElementById('myTooltip'); if (tooltip) { tooltip.style.opacity = '0'; // 延遲display: none,給CSS transition留時間 setTimeout(() => tooltip.style.display = 'none', 300); } });
// 假設你有表格數據 const tableData = [ { product: 'A', stock: 10, price: 100 }, { product: 'B', stock: 3, price: 50 }, // 低庫存 { product: 'C', stock: 20, price: 200 } ]; function renderTable(data) { const tableBody = document.querySelector('#myTable tbody'); tableBody.innerhtml = ''; // 清空現有內容 data.forEach(item => { const row = tableBody.insertRow(); const stockCell = row.insertCell(); stockCell.textContent = item.stock; if (item.stock < 5) { // 假設庫存小于5是異常 stockCell.classList.add('low-stock-alert'); } // ... 其他單元格 }); } // CSS中定義 .low-stock-alert { background-color: #ffe0e0; color: #d32f2f; }
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END