jQuery手風琴圖片切換

antzone發表於2018-02-06

本章節分享一段程式碼例項,它實現了簡單的手風琴圖片切換效果。

當滑鼠懸浮和離開,當前圖片就會伸縮尺寸。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
* {
  margin: 0;
  padding: 0;
}
.box {
  width: 1174px;
  height: 405px;
  margin: 0 auto;
  overflow: hidden;
}
li {
  float: left;
  list-style: none;
  width: 106px;
  overflow: hidden;
  height: 405px;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script>
$(function () {
  $("ul li").mouseover(function () {
    $(this).stop().animate({ width: 538 }, 500);
    $(this).siblings().stop().animate({ width: 106 }, 500)
  })
})
</script>
</head>
<body>
<div class="box">
  <ul>
    <li style="width:538px;"><img src="demo/jQuery/img/a.jpg"></li>
    <li><img src="demo/jQuery/img/b.jpg"></li>
    <li><img src="demo/jQuery/img/c.jpg"></li>
    <li><img src="demo/jQuery/img/d.jpg"></li>
    <li><img src="demo/jQuery/img/e.jpg"></li>
    <li><img src="demo/jQuery/img/f.jpg"></li>
    <li><img src="demo/jQuery/img/g.jpg"></li>
  </ul>
</div>
</body>
</html>

上面的程式碼實現了我們的要求,下面介紹一下它的實現過程。

一.實現原理:

原理其實非常的簡單,就是通過滑鼠懸浮來調整當前li元素的寬度和其他li元素的寬度,以此來達到視覺上圖片伸縮的效果,所謂的伸縮其實就是設定圖片被overflow:hidden尺寸的大小而已。

二.程式碼註釋:

(1).$(function () {}),當文件結構完全載入完畢再去執行函式中的程式碼。

(2).$("ul li").mouseover(function () {}),為li元素註冊mouseover事件處理函式。

(3).$(this).stop().animate({ width: 538 }, 500),以動畫方式設定當前li元素的寬度為538px,stop()方法的作用是為了防止滑鼠快速反覆懸浮離開,導致動作重複執行的現象。

(4).$(this).siblings().stop().animate({ width: 106 }, 500),當前懸浮元素的其他的元素的寬度以動畫方式設定為106px。

三.相關閱讀:

(1).mouseover事件參閱jQuery mouseover事件一章節。

(2).animate()參閱jQuery animate()一章節。

(3).siblings()參閱jQuery siblings()一章節。

(4).stop()參閱jQuery stop()一章節。

相關文章