美文网首页
js手风琴

js手风琴

作者: 霁雨轩阁 | 来源:发表于2018-09-26 23:09 被阅读0次

    CSS部分

    <style type="text/css">
    *{
    padding: 0;
    margin: 0;
    }
    #box{
    width: 1150px;
    height: 400px;
    border: 1px solid silver;
    margin: 200px auto;
    overflow: hidden;
    }
    ul{
    list-style: none;
    }
    ul li{
    width: 240px;
    height: 400px;
    float: left;
    }
    #box ul{
    width: 1300px;
    }
    </style>

    html部分
    <div id="box">
    <ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    </ul>
    </div>

    JS部分
    <script type="text/javascript">
    var box=document.getElementById("box");
    var arr=document.getElementsByTagName("li");
    for(i=0;i<arr.length;i++){
    arr[i].style.background="url(img/"+(i+1)+".jpg) no-repeat";
    arr[i].onmouseover=function(){
    for(j=0;j<arr.length;j++){
    animate(arr[j],{"width":100});
    }
    animate(this,{"width":800});
    }
    }
    box.onmouseout=function(){
    for(j=0;j<arr.length;j++){
    animate(arr[j],{"width":240});
    }
    }

        </script>
    

    用到的运动封装函数:
    function getStyle(ele,attr){
    if(window.getComputedStyle){
    return window.getComputedStyle(ele,null)[attr];
    }
    return ele.currentStyle[attr];
    }

    //参数变为3个
    function animate(ele,json,fn){
    //先清定时器
    clearInterval(ele.timer);
    ele.timer = setInterval(function () {
    //开闭原则
    var bool = true;

        //遍历属性和值,分别单独处理json
        //attr == k(键)    target == json[k](值)
        for(var k in json){
            //四部
            var leader = parseInt(getStyle(ele,k)) || 0;
            //1.获取步长
            var step = (json[k] - leader)/10;
            //2.二次加工步长
            step = step>0?Math.ceil(step):Math.floor(step);
            leader = leader + step;
            //3.赋值
            ele.style[k] = leader + "px";
            //4.清除定时器
            //判断: 目标值和当前值的差大于步长,就不能跳出循环
            //不考虑小数的情况:目标位置和当前位置不相等,就不能清除清除定时器。
            if(json[k] !== leader){
                bool = false;
            }
        }
    
        console.log(1);
        //只有所有的属性都到了指定位置,bool值才不会变成false;
        if(bool){
            clearInterval(ele.timer);
            //所有程序执行完毕了,现在可以执行回调函数了
            //只有传递了回调函数,才能执行
            if(fn){
                fn();
            }
        }
    },1);
    

    }


    1EF706200D789F0CD30AC6115822535F.png

    相关文章

      网友评论

          本文标题:js手风琴

          本文链接:https://www.haomeiwen.com/subject/sxhsoftx.html