DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS進階教程
純 CSS 換頁效果:不用 JavaScript 切換圖片與清單
編輯:CSS進階教程     

想看第二張圖卻不必載入新頁面?其實不需要 JavaScript,靠錨點(anchor)加上絕對定位就能做出簡單的換頁效果。原理是讓每張圖各自帶一個 id,再用 href="#id" 把視窗的目標位置對準它,外層容器用 overflow: hidden 裁掉多餘部分。

範例一:圖片輪播

<style>
dl {
  position: absolute;
  width: 240px;
  height: 170px;
  border: 10px solid #eee;
}
dd {
  margin: 0;
  width: 240px;
  height: 170px;
  overflow: hidden;
}
img { border: 1px solid black }
dt {
  position: absolute;
  right: 3px;
  top: 50px;
}
a {
  display: block;
  margin: 1px;
  width: 20px;
  height: 20px;
  text-align: center;
  font: 700 12px/20px "新細明體", sans-serif;
  color: #fff;
  text-decoration: none;
  background: #666;
  border: 1px solid #fff;
  filter: alpha(opacity=40);
  opacity: .4;
}
a:hover { background: #000 }
</style>

<dl>
  <dt>
    <a href="#a">1</a><a href="#b">2</a><a href="#c">3</a>
  </dt>
  <dd>
    <img src="1.jpg" id="a" alt="" />
    <img src="2.jpg" id="b" alt="" />
    <img src="3.jpg" id="c" alt="" />
  </dd>
</dl>

三個數字按鈕半透明地疊在右上,滑過時變得不透明,點下去就跳到對應的錨點。

範例二:分頁式新聞列表

同樣的思路換個殼,就能做出標籤頁式的清單切換。這次用 ul 承載三組清單,靠背景圖的 background-position 變化來表示目前所在的分頁:

<style>
dl { position: absolute; width: 240px; height: 170px; border: 10px solid #eee; }
dd { margin: 0; width: 240px; height: 170px; overflow: hidden; }
dt { position: absolute; right: 1px; }

ul {
  margin: 0;
  padding: 0;
  width: 260px;
  height: 170px;
  list-style: none;
  background: url("arrow.gif") no-repeat 75% 20px;
  border: 1px solid #ccc;
}
#b { background-position: 75% center }
#c { background-position: 75% 86% }

li {
  width: 205px;
  height: 27px;
  font: 12px/27px "新細明體", sans-serif;
  white-space: nowrap;
  overflow: hidden;
}

dt a {
  display: block;
  margin: 1px;
  width: 30px;
  height: 56px;
  text-align: center;
  font: 700 12px/55px "新細明體", sans-serif;
  color: #fff;
  text-decoration: none;
  background: #666;
}
dt a:hover { background: orange }
</style>

<dl>
  <dt><a href="#a">新聞</a><a href="#b">娛樂</a><a href="#c">體育</a></dt>
  <dd>
    <ul id="a"><li>...</li></ul>
    <ul id="b"><li>...</li></ul>
    <ul id="c"><li>...</li></ul>
  </dd>
</dl>

三個 ul 疊在同一個位置,靠錨點決定誰被看見,右側的箭頭背景則依目前 id 對齊到不同高度,讓使用者知道現在停在哪一頁。

這招的邊界

純 CSS 換頁的優點是零腳本、失效風險低;缺點也很明確——無法自動輪播、無法記錄狀態,而且每次切換都會改動網址的 hash。若需要自動播放或循環,還是得回到 JavaScript。但作為「用所學元素湊出效果」的練習,這個範例示範了 overflow、position 與錨點三者搭配時能擦出什麼火花,值得举一反三。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved