表格欄位、卡片標題等空間有限時,常需「超出隱藏+懸停顯示完整」。純 CSS 方案最輕量,JS 方案靈活。
.ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 200px; /* 必須有寬度限制 */
}
.ellipsis:hover {
overflow: visible;
white-space: normal;
position: relative;
z-index: 1;
background: #fff;
box-shadow: 0 2px 8px rgba(0,0,0,.15);
padding: 2px 4px;
}
<span class="ellipsis" title="完整內容">超長文字內容...</span> 同時保留 title 作為無 JS 兜底。
function truncate(str, maxLen = 40) {
if (str.length <= maxLen) return str;
const half = Math.floor((maxLen - 3) / 2);
return str.slice(0, half) + '...' + str.slice(-half);
}
// 使用
document.querySelectorAll('[data-truncate]').forEach(el => {
const full = el.textContent;
el.dataset.full = full;
el.textContent = truncate(full);
el.addEventListener('mouseenter', () => el.textContent = full);
el.addEventListener('mouseleave', () => el.textContent = truncate(full));
});
<a title="${item.url}">
<c:choose>
<c:when test="${fn:length(item.url) ge 40}">
${fn:substring(item.url,0,20)}...${fn:substring(item.url, fn:length(item.url)-20)}
</c:when>
<c:otherwise>${item.url}</c:otherwise>
</c:choose>
</a>