萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

長文字截斷顯示 + 滑鼠懸停全文:CSS 與 JS 兩種方案

表格欄位、卡片標題等空間有限時,常需「超出隱藏+懸停顯示完整」。純 CSS 方案最輕量,JS 方案靈活。

方案一:純 CSS(推薦)

.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 兜底。

方案二: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));
});

原始 JSP/JSTL 邏輯(參考)

<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>

選型建議

  • 靜態內容、單行、SEO 需可見全文 → CSS。
  • 動態數據、多行、需首尾語義(如 URL)、需複製全文 → JS。
copyright © 萬盛學電腦網 all rights reserved