// by ifmiss // github: https://github.com/ifmiss/moveline // 菜单鼠标悬浮移动效果 (function(){ //底部的菜单移动效果 $.fn.moveline = function(options,callback){ var _this = this; var $this = $(this); var defaultvalue = { height:2, //高度 position:'', //线条是显示在内部 inner是在内部 color:'#f74f37', //颜色 animatetime:500, //毫秒 animatetype:'easeoutback', //动画效果 //没有引用jquery.easing.js 的话 为''就行。 zindex:'1', //层级 top:0, //自定义top customtop:false, //是否自定义top randomcolor:false, //是否显示随机色线条 randomopacity:1, //透明度 click:function(){}, //点击菜单触发的效果 } var opt = $.extend(defaultvalue,options || {}); $this.css({ position:'relative', }); //li的margin 宽 var li_width = $this.children().outerwidth(); //li的margin 高 也是之后滚动线条的top值 var li_height = opt.position === 'inner'? $this.children().outerheight() - opt.height : $this.children().outerheight(); //红线的left位置 //var li_left = $this.children().position().left; var li_left = 65; //li的margin left var li_marginleft = number($this.children().css('margin-left').replace(/[^0-9]+/g, '')); //是否显示随机颜色 var randomcolor = function(){ var opacity = opt.randomopacity || 1; var r=math.floor(math.random()*256); var g=math.floor(math.random()*256); var b=math.floor(math.random()*256); return "rgba("+r+','+g+','+b+','+opacity+")"; }; var color = opt.randomcolor? randomcolor() : opt.color; if(opt.customtop) li_height = opt.top; var zindex = opt.height > 5 ? '-1':opt.zindex; // 定义底部滚动线条 _this.movelinediv = $('').css({ 'position': 'absolute', 'height': opt.height, 'background': color, 'top':li_height, 'z-index':zindex, }).appendto($this); //判断li中有active 的索引 并获取其left的值 for(var i = 0; i<$this.children().length;i++){ if ($this.children().eq(i).hasclass('active')) { li_left = $this.children().eq(i).position().left; li_width = $this.children().eq(i).outerwidth(); } } // 初始化红线进去 _this.movelinediv.stop().animate({ width:li_width, left:li_left + li_marginleft }, opt.animatetime,opt.animatetype); //红线的hover效果 $this.children().hover(function(){ var li_marginleft = number($this.children().css('margin-left').replace(/[^0-9]+/g, '')); var li_width = $(this).outerwidth(); var li_left = $(this).position().left; _this.movelinediv.stop().animate({ width:li_width, left:li_left + li_marginleft }, opt.animatetime,opt.animatetype); },function(){ for(var i = 0; i<$this.children().length;i++){ if ($this.children().eq(i).hasclass('active')) { li_left = $this.children().eq(i).position().left; li_width = $this.children().eq(i).outerwidth(); } } _this.movelinediv.stop().animate({ width:li_width, left:li_left + li_marginleft }, opt.animatetime); }); $this.children().on('click',function(){ var ret = { ele:$(this), index:$(this).index(), } opt.click(ret); //未写回调函数则不会有效果 // if(typeof(callback) === 'function'){ // callback(ret); // }else{ // console.error('you need a click event callback function, which needs to be written in the callback after defining the plugin!'); // } }); return _this; } })(jquery)