滑鼠移到文字區塊上,原本被省略號截斷的內容完整展開——這個互動在資訊列表、卡片摘要與文章預覽中隨處可見。這一節就把它的做法完整走一遍。
實現代碼如下:
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>CSS3實現鼠標移上去顯示全部內容</title>
<style type="text/css">
#container {
text-overflow:ellipsis;
overflow:hidden;
white-space:nowrap;
border:1px solid gray;
width:300px;
padding:20px;
color:raba(0,0,0,0.7);
cursor:pointer;
}
#container:hover {
white-space:normal;
height:148px;
background-color:#F2F9F9;
transition-property:background-color,height;
transition-duration:0.2s ;
transition-timing-function:linear;
}
</style>
</head>
<body>
<div id="container"> 學習網成立於2015年4月1日,是一個富有活力的技術學習網站。 學習網為廣大網絡工作者(網頁開發人員、站長等)提供各種精品教程以及最精華資料。 學習網跟其他垃圾采集站不一樣, 學習網中的每一個課程、每一篇文章,甚至每一個知識點,都凝聚了本人的最辛勤的汗水。</div>
</body>
</html>
分析:
滑鼠移入後,被摺疊的內容會逐漸展開,背景色同步轉為淺色。
這裡用到兩個技術點。第一是單行省略:文字超出範圍時以省略號收尾並隱藏多餘內容,必須靠這三行搭配:
text-overflow:ellipsis; overflow:hidden; white-space:nowrap;
三者缺一不可:white-space:nowrap 讓文字不換行,overflow:hidden 讓超出的部分被裁掉,text-overflow:ellipsis 則負責在裁切處畫上省略號。
第二是過渡::hover 時把 white-space 改回 normal 讓文字換行,同時指定 height 由 0 過渡到 148px,於是展開的過程看起來是平滑的長高,而不是硬邦邦地彈開。