(function($){ $.fn.getselfindex=function(type){ if(typeof(type)=="undefined"){ //在同辈元素均为同类型的元素时 return $(this).prevall().length; }else { //在同辈元素有多种类型时 return $(this).prevall().filter(type).length; } }; })(jquery); $(function () { var speed = 1, autotime = 5000; var movepx, ind, len, timer; window.onresize = function () { window.cleartimeout(timer); nav_init(); timer = window.settimeout(function () { automove(); }, autotime); } function nav_init() { movepx = $('.photoshow').width(), ind = $('.photoshow .current').getselfindex('.photoshow li'), len = $('#photoshow li').length; this.navobj = $('#nav'); this.ul = $('.photoshow ul'); this.li = $('.photoshow ul li'); //this.parentwidth = this.navobj.parent().width(); this.parentwidth = this.navobj.parent().width(); this.left = (this.parentwidth - this.navobj.width()) / 2; //this.navobj.css({'left': this.left}); this.ul.css({ width: movepx * len + 'px','marginleft': -movepx * ind+'px' }); this.li.css({ width: movepx + 'px' }); } function nav_change(next) { $('#nav em').removeclass('ehover').eq(next).addclass('ehover'); } function moveto(to) { var gotoit; ind = $('.photoshow .current').getselfindex('.photoshow li'); //console.log('当前: ' + ind); if ((to == '' || to == null || to == 'undefined') && to != 0) { gotoit = ind < len - 1 ? ind + 1 : 0; } else { //console.log('选择:' + to); gotoit = to < 0 ? len - 1 : to > len - 1 ? 0 : to; } //console.log('下个: ' + goto); //console.log('--------------------'); $('.photoshow li').removeclass('current').eq(gotoit).addclass('current'); $('#photoshow').animate({ 'marginleft': -movepx * gotoit }, speed); nav_change(gotoit); } function automove() { moveto(); timer = window.settimeout(function () { automove(); }, autotime); } nav_init(); timer = window.settimeout(function () { automove(); }, autotime); $('#left').click(function () { ind = $('.photoshow .current').getselfindex('.photoshow li'); moveto(ind - 1); }); $('#right').click(function () { ind = $('.photoshow .current').getselfindex('.photoshow li'); moveto(ind + 1); }); $('#nav em').click(function () { var ind_nav = $(this).getselfindex('#nav em'); moveto(ind_nav); }); $('#nav').mouseover(function () {window.cleartimeout(timer); }).mouseout(function () { timer = window.settimeout(function () { automove(); }, autotime); }); });