DIV CSS 佈局教程網

以 jQuery 實作數字式圖片切換效果
編輯:JQuery特效代碼     

效果說明

本篇實作一個以數字作為切換控制項的圖片輪播:滑鼠移入數字時會有視覺回饋,點擊數字即可切換上方顯示的對應圖片。整體結構簡單,很適合當作 jQuery 入門練習。

樣式設定

先為滑鼠移入狀態加上樣式:

<style type="text/css">
.mouseOver {
  cursor: hand;
  border: 1px solid red;
}
</style>

圖片切換的 JavaScript

<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
var imgPaths = [
  "https://files.jb51.net/demoimg/201008/o_p1.jpg",
  "https://files.jb51.net/demoimg/201008/o_p3.jpg"
];
$(function () {
  $("#showImg").attr("src", imgPaths[0]);
  var top, left, width, height;
  top = $("#showImg").offset().top;
  left = $("#showImg").offset().left;
  width = $("#showImg").width();
  height = $("#showImg").height();
  // 將數字控制項定位在圖片右下角
  $("#popDiv").css({
    position: "absolute",
    top: top + height - $("#popDiv").height(),
    left: left + width - $("#popDiv").width(),
    padding: "1px"
  });
  $("#popDiv span").hover(function () {
    $(this).addClass("mouseOver");
  }, function () {
    $(this).removeClass("mouseOver")
  }).click(function () {
    // 依點擊的數字切換對應圖片
    $("#showImg").attr("src", imgPaths[eval($(this).text()) - 1]);
  });
});
</script>

HTML 結構

<div>
  <img id="showImg" alt="" height="400" width="300" src="" />
</div>
<div id="popDiv" style="width:300px;height:20px;text-align:right">
  <span>1</span>
  <span>2</span>
</div>

重點說明

這個範例的巧妙之處在於:先用 offset()、width()、height() 取得大圖的位置與尺寸,再據此把數字控制項精準定位在圖片的右下角;接著透過 hover() 切換滑鼠移入樣式,並以 click() 事件讀取被點擊數字的文字,換成陣列索引來切換圖片來源。將這段程式碼複製到自己的頁面裡運行,就能立即看到效果;若想追求更精美的呈現,也可以在此基礎上自由調整樣式與動畫。

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