手风琴切换效果

2016-12-26  本文已影响0人  妙言Lisa

手风琴图片切换效果,一个很简单的效果,本来没什么思路,不过还是通过自己的思考和尝试,完全实现出来了。看来要经常写写这种小效果增加一点自信。

样式:

样式上没难度,主要是用绝对定位+nth-child。两个注意点:

  1. .wrap用了overflow:hidden,图片滑动时还是会超出并出现滚动条。因为我没有设置父元素relative
  2. 用jQuery使IE8及以下兼容nth-child
  3. 用PIE.htc使IE6-8兼容border-radius,只要在设置了border-radius的元素css中增加这一句behavior:url(PIE.htc);
  4. 使IE6-8兼容rgba,主要是加上以下这句:
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#7F000000,endColorstr=#7F000000);
    其中的7F是alpha255换成16进制*,常用的rgba和IE下filter数值的转换:
    rgba透明值:0.1  0.2  0.3  0.4  0.5  0.6  0.7  0.8  0.9
    IE下filter值:19   33   4c   66   7f   99   b2   c8   e5
    参考博文

实现思路:

实现重点:

  1. position().left取得当前的left,用index()取得当前的索引值
  2. nextAll()取得所有后面的元素,用slice(1,$(this).index()+1)取得从第2张到当前张的所有元素
  3. each()来遍历
  4. animate实现动画
  5. 关键代码如下:
<script type="text/javascript">
    $(document).ready(function(){
        //nth-child: 兼容IE8及以下
        $(".wrap .item:nth-child(2)").css("left","120px");
        $(".wrap .item:nth-child(3)").css("left","240px");
        $(".wrap .item:nth-child(4)").css("left","360px");
        $(".wrap .item:nth-child(5)").css("left","480px");

        //鼠标移入图片事件
        $(".wrap .item").click(function(){
            var imgLeft=$(this).position().left;  //目标图片的当前left值
            var targetLeft=$(this).index()*120; //目标图片应有的left值
            if(imgLeft==targetLeft){  //说明只需移动目标的后几张图片
                $(this).nextAll().each(function(){ //获取后面的几张图片进行遍历
                    $(this).animate({
                        left:$(this).index()*120+600+"px" //600是图片展开增加的宽度
                    })
                })
            }else{  //否则,需要移动目标和前几张图片(除了第一张)
                $(".wrap .item").slice(1,$(this).index()+1).each(function(){
                    $(this).animate({
                        left:$(this).index()*120+"px"
                    })
                })
            }
        })
    })
</script>

兼容性:

兼容Chrome, Firefox, IE6及以上

上一篇 下一篇

猜你喜欢

热点阅读