在不用寫程式的情況下,透過 CSS 的屬性來做出一些互動效果,連自己看了都覺得很猛阿!! 如果研究的夠徹底,還可以做出許多超炫的效果,整個網頁就是你的專屬畫布。

一開始就先說明一下想要這次的目標想做到什麼效果吧,在網路上應該還蠻常見到這種廣告的,當滑鼠移到一張圖片上時,使圖片變模糊,並且出現說明文字的區塊蓋住這張圖片。

做完的效果就如下所示 (行動裝置可請點選圖片看效果)

廢話不多說,就開始示範怎麼做出這個效果。

首先我們需要一個容器,這個容器會包著圖片以及文字的部分,接著再用一個容器裝文字,所以我們先做出這些容器。

1
2
3
4
5
6
7
8
<div class="adBorder">
<img>
    <!-- text -->
    <div class="adTextContainer">

    </div>

</div>

接著把內容放進去,設定圖片來源,而文字的部分,使用 <P> 標籤,分別寫上標題、敘述內容以及來源。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<div class="adBorder">
      <!-- img -->
    <div class="adImgContainer">
      <img class="adImg"  src="https://i.ytimg.com/vi/V18tyItqJrw/maxresdefault.jpg">   
    </div>
    <!-- text -->
    <div class="adTextContainer">
     <p class="adTitle"> BMW 7 Series</p>
      <p class="adDes"> The BMW 7 Series is a full-size luxury sedan produced by the German automaker BMW since 1977. It is the successor to the BMW E3 "New Six" sedan and is currently in its sixth generation.
</p>
      <p class="adSponsored"> Reference:WIKI</p>
    </div>

</div>

HTML的部分就只需要這樣,接著就要使用 CSS 來調整樣式以及做出我們要的效果了。

設定最外層的容器寬度與高度,並且設定 position:relative; 這樣到時文字的部分才可以設定相對位置來副蓋在圖片上。

.adBorder{
  width:520px;
  height:292px;
  position:relative;
}

接著幫圖片設定寬高。

.adImg{
  border:0;
  width: 100%;
  height: 100%;
}

接著設定文字部分的樣式,因為所有文字是放在同一個容器裡,因此我們先針對這個容器設定屬性,設定好 position:absolute; 並且設定 top:0px; left:0px; 固定好他與上層容器的相對位置,這時文字的容器就蓋在圖片上了。 background-color 使用 rgba 設定不透明度,這樣就能看到被蓋在後面的圖,因為要做滑鼠移到容器上才出現文字的部分,因此先把 opacity 設定成 0,再來就是利用 transition 的屬性設定屬性改變時的動畫效果,文字容器部分設定好之後,再幫標題、內容敘述等文字加上樣式。 內容敘述的部分,因為有換行, text-align 設定 justify,可以讓文字排滿對齊,是個很好用的屬性。

.adTextContainer{
  position:absolute;
  top:0px;
  left:0px;
  padding-top:74px;
  background-color:rgba(255, 255, 255, 0.7) ;
  height:292px;
  width: 520px;
  opacity:0;
  -webkit-transition: opacity 0.8s,
                      padding 0.3s linear;
  transition: opacity 0.8s,
              padding 0.3s linear;
}

.adTitle {
  color:#000000;
  font-size: 26px;
  font-family: Helvetica;
  font-weight:bold;
  overflow : hidden;
  width: 70%;
  line-height: 30px;
  margin: 0px auto 0px auto;
}

.adDes{
  color:#333;
  text-align:justify;
  font-size:14px;
  font-family: Helvetica;
  margin: 20px auto 0 auto;
  width: 70%;
}

.adSponsored{
color:#000;
font-size: 13px;
width: 70%;
margin: 20px auto 63px auto;
font-family: Helvetica;
line-height:18px;
}

接下來就是最後的步驟了,使用 hover 來設定滑鼠移到容器上面時改變屬性而做出動畫的效果,這邊設定為當滑鼠移到最上層的套用 adBorder 這個 class 的 div 時, img 會變模糊,如何使圖片變模糊呢? 只需要設定 filter: blur(3px) 即可。 而這個時候,文字的區塊必須出現,因此 adTextContainer 這個 class 的 opacity 要調整為 1 ,再加上 padding-top 使位置變動,有文字向上浮動的效果。

.adBorder:hover img {  
  -webkit-filter: blur(3px);
  filter: blur(3px);
}
.adBorder:hover .adTextContainer {
  padding-top:64px;
  opacity: 1;  
}

不用寫任何的 javascript ,就能做到的效果,是不是迅速又方便呢?

完整的程式碼如下:

點此可以看完整程式碼範例

Comments