jQuery实现多张图片上下叠加切换

2025-11-19 20:46:01

1、先在div容器中加入一堆图片

本帖中的图片都用http://placehold.it/300x250来代替

<div id="gallery">

<div id="pictures">

<img src="http://placehold.it/300x250&text=Item1" alt="" />

<img src="http://placehold.it/300x250&text=Item2" alt="" />

<img src="http://placehold.it/300x250&text=Item3" alt="" />

<img src="http://placehold.it/300x250&text=Item4" alt="" />

<img src="http://placehold.it/300x250&text=Item5" alt="" />

</div>

</div>

jQuery实现多张图片上下叠加切换

2、为了实现杂乱的效果,对img添加如下css。本例用的是chrome浏览器,其它浏览器请自行更改前缀

div img:nth-child(even) {

    -webkit-transform: rotate(10deg);

    margin-left:5px;

}

div img:nth-child(3n) {

    -webkit-transform: rotate(-15deg);

}

其结果如下图

jQuery实现多张图片上下叠加切换

3、对所有的img添加z-index

var z = 0;

$('#pictures img').each(function() { 

    z++; 

    $(this).css('z-index', z); 

});

4、新增点击图片事件

$('#pictures').click(function() {

   return swapFirstLast(); 

});

5、实现swapFirstLast

首先,只让最上层的,也就是z-index最大的那个上移->z-index制为最小->还原位置

$(this).animate({ 'top' : '-' + $(this).height() + 'px' }, 'slow', function() { 

     $(this).css('z-index', 1) 

         .animate({ 'top' : '0' }, 'slow', function() { 

         });

 });

其它图片则把各自的z-index加1

$(this).css('z-index', parseInt($(this).css('z-index')) +1 ) ;

//完整代码

function swapFirstLast() {

    $('#pictures img').each(function() {

        if($(this).css('z-index') == z) {

            $(this).animate({ 'top' : '-' + $(this).height() + 'px' }, 'slow', function() {

                $(this).css('z-index', 1)

                    .animate({ 'top' : '0' }, 'slow', function() {

                    });

            });

        } else {

            $(this).css('z-index', parseInt($(this).css('z-index')) +1 ) ;

        }

    });

    return false;

  }

6、所有代码如下

jQuery实现多张图片上下叠加切换

7、css代码如下

@charset "utf-8";

*{margin:0;padding:0;list-style-type:none;}

body{font:12px/180% "微软雅黑";background:#22384d;color:#555555;}

#gallery{position:relative;width:460px;margin:40px auto 0 auto;}

#pictures{position:relative;height:408px;}

#pictures img{position:absolute;top:0;left:0;}

jQuery实现多张图片上下叠加切换

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
相关推荐
  • 阅读量:67
  • 阅读量:100
  • 阅读量:171
  • 阅读量:181
  • 阅读量:181
  • 猜你喜欢