Web 開發中,「文字怎麼排」與「元素到底多寬多高」是兩類反覆出現的問題。前者靠 CSS 屬性,後者靠 jQuery 的寬高方法,以下分別整理。
normalkeep-allbreak-allnormalbreak-wordnormalprenowrap<br>。pre-wrappre-linenone 保留原樣;capitalize 每字首字母大寫;uppercase 全大寫;lowercase 全小寫;full-width 轉為全形。
clip 直接裁切;ellipsis 以省略號表示。要生效必須同時設定 white-space:nowrap 與 overflow:hidden,且這兩行要寫在 text-overflow 之前。
可接受長度或百分比,可以為負值(常用來做文字隱藏技巧)。hanging 讓縮排作用於首行以外的行;each-line 則作用於每一行。
可用 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>
三組方法,差別在「算不算 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 的暫時手法。