My Book

筋斗云特效

原生js

window.onload = function (){
        var liArr = document.getElementsByTagName("li");
        var liWidth  = liArr[0].offsetWidth;
        var span = document.getElementsByTagName("span")[0];
        var count = 0;
        for(var i=0;i<liArr.length;i++){
            liArr[i].index = i;
            liArr[i].onmouseover = function (){
                animate(span,this.index*liWidth);
            };
            liArr[i].onmouseout = function (){
                animate(span,count*liWidth);
            };
            liArr[i].onclick = function (){
                count = this.index;
                animate(span,count*liWidth);
            };
        //封装一个方法
        function animate(ele,target){
            clearInterval(ele.timer);
            ele.timer = setInterval( function (){
                var step = (target-ele.offsetLeft)/10;
                step = step>0?Math.ceil(step):Math.floor(step);
                ele.style.left = ele.offsetLeft +step +"px";
                console.log(1);
                if(Math.abs(target-ele.offsetLeft)<Math.abs(step)){
                    ele.style.left = target+"px";
                    clearInterval(ele.timer);
                }
            },20)
        }
        }
    }

jquery

//动态获取线条的宽度以及距离左边的距离
$(".nav ul li").mouseover(function(){
    var width = this.offsetWidth;
    var left = this.offsetLeft;
    $("#nav-line").fadeIn(200).css({"width":width,"left":left});
});
//离开nav,横线消失,mouseleave是不会冒泡的
$(".top-nav").mouseleave(function(e){
   $("#nav-line").fadeOut(20);
});