DIV CSS 佈局教程網

CSS 文字相關樣式與 jQuery 取得元素寬高,分別說明
編輯:JQuery特效代碼     

Web 開發中,「文字怎麼排」與「元素到底多寬多高」是兩類反覆出現的問題。前者靠 CSS 屬性,後者靠 jQuery 的寬高方法,以下分別整理。

一、CSS 的文字樣式

1. word-break:單詞在容器邊界如何處理

normal
瀏覽器預設行為。
keep-all
遇到容器邊界時,單詞內部不換行( CJK 文字不受限制)。
break-all
遇到邊界就允許在單詞中間斷開換行。

2. word-wrap:內容超出邊界時是否斷行

normal
內容可以撐開或溢出容器。
break-word
內容在容器邊界處換行,不溢出。

3. white-space:空白與換行的處理

normal
預設:空白合併,超出自動換行。
pre
保留空白與換行,且超出也不換行。
nowrap
強制單行顯示,合併多餘空白,直到遇到 <br>。
pre-wrap
保留空白,但超出邊界時會換行。
pre-line
合併相鄰空白,保留換行符號,超出會換行。

4. text-transform:大小寫轉換

none 保留原樣;capitalize 每字首字母大寫;uppercase 全大寫;lowercase 全小寫;full-width 轉為全形。

5. text-overflow:溢出內容的處理

clip 直接裁切;ellipsis 以省略號表示。要生效必須同時設定 white-space:nowrap 與 overflow:hidden,且這兩行要寫在 text-overflow 之前。

6. text-indent:首行縮排

可接受長度或百分比,可以為負值(常用來做文字隱藏技巧)。hanging 讓縮排作用於首行以外的行;each-line 則作用於每一行。

7. line-height:行高

可用 normal、絕對長度、百分比或倍數。實務上建議用無單位倍數(如 line-height: 1.6),因為百分比與倍數在繼承時的計算方式不同,無單位倍數能讓子元素依自己的 font-size 重新計算,比較不會出錯。

省略號範例

<div style="border:1px solid red; width:500px;
            white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">
這裡文本超出容器時將以省略號顯示, text... text... abc6666666666666
</div>

二、jQuery 取得元素寬高

三組方法,差別在「算不算 padding/border/margin」:

$("#div_id").height();          // 元素本身高度(不含 padding / border / margin)
$("#div_id").width();

$("#div_id").outerHeight();     // 高度 + padding + border(不含 margin)
$("#div_id").outerWidth();

$("#div_id").outerHeight(true); // 高度 + padding + border + margin(全部計入)
$("#div_id").outerWidth(true);

實測驗證

<div id="testDiv" style="margin:10px 5px; width:600px; padding:10px 20px;
     height:60px; border:2px solid red;">
div info: height 60px, width 600px, padding 10px 20px, margin 10px 5px
</div>
<input type="button" value="TEST" id="btnTest" onclick="testHeight();" />

<script type="text/javascript">
function testHeight() {
    var obj = $('#testDiv');
    alert('height            = ' + obj.height());          // 60
    alert('outerHeight       = ' + obj.outerHeight());     // 60 + 20 + 4 = 84
    alert('outerHeight(true) = ' + obj.outerHeight(true)); // 84 + 20 = 104
    alert('width             = ' + obj.width());           // 600
    alert('outerWidth        = ' + obj.outerWidth());      // 600 + 40 + 4 = 644
    alert('outerWidth(true)  = ' + obj.outerWidth(true));  // 644 + 10 = 654
}
</script>

選用建議

  • 要做置中計算(例如彈窗定位),用 outerHeight(true)/outerWidth(true),因為它才是元素實際佔掉的全部空間。
  • 要讀內容區大小做滾動或換行判斷,用 height()/width()。
  • 若 box-sizing: border-box 已套用,height() 回傳的仍是內容區扣除 padding 後的值,這點在計算時容易忘記。
  • 元素隱藏時(display:none)所有寬高都會是 0,記得先 show() 再量,或改用 position:absolute; visibility:hidden 的暫時手法。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved