這里介紹兩種方法,都是css實現的,其他的js,jq代碼,可以去網上搜索很多。
第一種:margin負值定位法
<div class="text_overflow" > <div class="text_con" >這是一段比較長的文字,用來測試是否文字溢出時會用省略號顯示。</div> <div class="text_dotted" >…</div>
.text_overflow{width:300px; height:25px; overflow:hidden;line-height:25px;border:1px solid #ccc;} .text_overflow .text_con{float:left;height:25px; margin-right:15px; overflow:hidden;} .text_overflow .text_dotted{ float:right;width:15px; height:26px;margin-top:-23px;margin-top:-30px\0;*margin-top:-23px;}
預覽效果為:
解釋:此段中text_dotted是單獨放省略號的標簽,當文字短時,省略號是隱藏在該文字所在行的上方,當文字內容足夠長時就把隱藏在上面的省略號層給擠下來了。關鍵就是省略號所在div層的高度的絕對值要比其margin的絕對值大,也就是height:26px。要比margin-top:-23px;大。注意此句中,因為要兼容ie的各個版本,所以寫了hack,導致ie8和ie9設置了更大的margin-top。
第二種:text-overflow:ellipsis+ ellipsis.xml
代碼如下:
<div class="slh">多出的文省略號表示多出的文省略號表示多出多出</div>
.slh{width:160px;height:50px;line-height:25px;border:4px solid #eee; white-space:nowrap;/*強制文本在一行內顯示*/ text-overflow:ellipsis; /*溢出省略號,支持ie、safari(webkit)*/ -o-text-overflow:ellipsis; /*溢出省略號,支持opera*/ overflow:hidden;/*溢出隱藏*/ -moz-binding:url('ellipsis.xml#ellipsis');/*溢出省略號,支持firefox*/}
預覽效果為:
解釋:如上css備注所示,注意-moz-binding:url('ellipsis.xml#ellipsis'); 這段中引用的xml文件,需要點擊下載,放在文件中,借鑒學習與張鑫旭的博客http://www.zhangxinxu.com/。