萬盛學電腦網

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

CSS/JS 文字溢出省略號 ellipsis 跨瀏覽器完整方案

現代標準方案(單行)

.ellipsis {
  width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

支援:IE6+、所有現代瀏覽器。

Firefox 早期版本 Hack(歷史參考)

Firefox 6 之前不支援 text-overflow,需用 XBL 綁定:

.ellipsis li {
  -moz-binding: url('ellipsis.xml#ellipsis'); /* 相對路徑 */
  white-space: nowrap; overflow: hidden; width: 200px;
}
ellipsis.xml:
<?xml version="1.0" encoding="utf-8"?>
<bindings xmlns="https://www.mozilla.org/xbl">
  <binding id="ellipsis">
    <content>
      <xul:description crop="end" xbl:inherits="value=xbl:text"><children/></xul:description>
    </content>
  </binding>
</bindings>

現代 Firefox (7+) 已原生支援,無需此 Hack。

jQuery 插件方案(舊專案維護)

$('.ellipsis').ellipsis(); // 需引入 jquery.ellipsis.js

PHP 伺服端截斷(備選)

function chinesesubstr($str, $start, $len) {
  $out = ''; $strlen = $start + $len;
  for ($i = $start; $i < $strlen; ) {
    if (ord($str[$i]) > 0xa0) { $out .= substr($str, $i, 2); $i += 2; }
    else { $out .= $str[$i]; $i++; }
  }
  return $out;
}
echo chinesesubstr($title, 0, 20) . '…';

多行省略(現代)

.multi-ellipsis {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
  line-height: 1.5; height: 4.5em; /* 3行高 */
}

標準化 line-clamp 正在推進,建議同時寫無前綴版本。

copyright © 萬盛學電腦網 all rights reserved