(function ( $ ) { $.fn.ilscroll=function(options){ var settings = $.extend({ s:45 }, options ); $this=this; $children=this.children(); $parent=this.parent(); $count=$children.size(); $margin=parseInt($children.css('margin-left'))+parseInt($children.css('margin-right')); $childrenwidth=$children.width()+$margin; $parentwidth=$parent.width(); $width=($count*$childrenwidth); if($width<$parentwidth){ return false; } $clone= $children.clone(); this.prepend($clone); this.width($width*2); $inter= setInterval(function(){ $marginleft=$this.css('margin-left'); $marginleft= parseInt($marginleft); $childh= parseInt($this.children().width()); if(Math.abs($marginleft)>=$width){ $this.css('margin-left',"0px"); }else{ $this.css('margin-left',$marginleft-1+"px"); } },settings.s); this.on('mouseover',function(){ clearInterval($inter); }); this.on('mouseout',function(){ $inter=setInterval(function(){ $marginleft=$this.css('margin-left'); $marginleft= parseInt($marginleft); $childh= parseInt($this.children().width()); if(Math.abs($marginleft)==$width){ $this.css('margin-left',"0px"); }else{ $this.css('margin-left',$marginleft-1+"px"); } },settings.s); }); }; }( jQuery ));
当子元素不比父元素宽时,不会发生滚动。
使用
$('.foo').ilscroll()
一个参数s用于控制速度.
修改用于应对margin-auto
(function ( $ ) { $.fn.ilscroll=function(options){ var settings = $.extend({ s:45 }, options ); $this=this; $children=this.children(); $parent=this.parent(); $count=$children.size(); $marginleft=$children.css('margin-left')=='auto'?0:parseInt($children.css('margin-left')); if($children.css){ } $children.css('margin-left','0px'); $children.css('margin-right','0px'); $margin=parseInt($children.css('margin-left'))+parseInt($children.css('margin-right')); $childrenwidth=parseInt($children.width())+$margin; $parentwidth=parseInt($parent.width()); $width=($count*$childrenwidth); if($width<$parentwidth){ return ; }else{ $clone= $children.clone(); this.prepend($clone); this.width($width*2); } $inter= setInterval(function(){ $marginleft=$this.css('margin-left'); if($marginleft==='auto'){ $marginleft=0; }else{ $marginleft=parseInt($marginleft); } $childh= parseInt($this.children().width()); if(Math.abs($marginleft)>=$width){ $this.css('margin-left',"0px"); }else{ $this.css('margin-left',(($marginleft)-1)+"px"); } },settings.s); this.on('mouseover',function(){ clearInterval($inter); }); this.on('mouseout',function(){ $inter=setInterval(function(){ $marginleft=$this.css('margin-left'); $marginleft= parseInt($marginleft); $childh= parseInt($this.children().width()); if(Math.abs($marginleft)==$width){ $this.css('margin-left',"0px"); }else{ $this.css('margin-left',$marginleft-1+"px"); } },settings.s); }); }; }( jQuery ));