「滑鼠移到圖片上,半透明遮罩從底部向上滑出顯示文字介紹,移開後遮罩退場。」這是在作品集、產品牆與圖片廊中最常見的互動之一,做法相當俐落。
實現代碼如下:
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>CSS3實現圖片文字介紹滑動展示效果</title>
<style type="text/css">
#info { width:760px; margin:0 auto; }
/*定義外層樣式*/
.wrap {
width:220px;
height:330px;
float:left;
position:relative;
overflow:hidden;
font-family:arial, sans-serif;
}
.wrap img { border:0; width:220px; height:330px; }
.wrap p {
display:block;
width:220px;
height:330px;
position:absolute;
left:0;
top:300px;
background-color:rgba(0,0,0,0.3);
/*使用CSS3 RGBA顏色值*/
font-size:12px;
color:#FFFFFF;
padding:0;
margin:0;
line-height:16px;
transition: all 0.6s ease-in-out;
/*定義CSS3過渡效果,all表示過渡屬性針對所有值有變化的CSS屬性*/
}
.wrap p b {
display:block;
font-size:22px;
color:#fc0;
text-align:center;
margin:0;
padding:0;
line-height:30px;
}
.wrap p span { display:block; padding:10px; line-height:20px; }
.wrap:hover p { top:0; }
</style>
</head>
<body>
<div id="info">
<div class="wrap">
<img src="../App_images/lesson/run_css3/pic1.jpg" alt="">
<p>
<b>Red Eye Frog</b>
<span>Red-eyed tree frogs, as their name states, have bold red eyes with vertically narrowed pupils, a vibrant green body with yellow and blue striped sides, and orange toes. There is a great deal of regional variation in flank and thigh coloration.<br/>Although it has been suggested that A. callidryas' bright colors function as aposematic or sexual signals, neither of these hypotheses have been confirmed.</span>
</p>
</div>
<div class="wrap">
<img src="../App_images/lesson/run_css3/pic2.jpg" alt="">
<p>
<b>Emperor Penguin</b>
<span>The Emperor Penguin (Aptenodytes forsteri) is the tallest and heaviest of all living penguin species and is endemic to Antarctica.<br><br>The male and female are similar in plumage and size, reaching 122 cm (48 in) in height and weighing anywhere from 22.37 kg (48.82 lb). The dorsal parts are black and sharply delineated from the white belly, pale-yellow breast and bright-yellow ear patches.</span>
</p>
</div>
<div class="wrap">
<img src="../App_images/lesson/run_css3/pic3.jpg" alt="">
<p>
<b>Pelicans</b>
<span>A pelican is a large water bird with a distinctive pouch under the beak, belonging to the bird family Pelecanidae.<br><br>Along with the darters, cormorants, gannets, boobies, frigatebirds, and tropicbirds, pelicans make up the order Pelecaniformes. Modern pelicans are found on all continents except Antarctica.</span>
</p>
</div>
</div>
</body>
</html>
分析:
滑鼠移入圖片時,文字層會平滑滑出覆蓋在圖片上;移開後再退回原位。
這個效果的原理其實很單純:.wrap 設定 position:relative 與 overflow:hidden,把文字層定位在 top:300px(幾乎完全藏在可視範圍外),滑鼠移入時把 top 改為 0,再交由 transition 處理中間過程。半透明底色則是靠 rgba(0,0,0,0.3) 完成,讓文字在照片上依然清晰可讀。
有個細節值得留意:前面章節都把 transition 寫在 :hover 裡,這裡卻寫在「.wrap p{}」上。差別在於,寫在 :hover 只會影響「移入」的過程,寫在元素本身則進出都會帶動畫——移開時同樣是平滑退場,而不是瞬間消失。