jQuery 幻灯片
jQuery 实现图片幻灯片
使用到的技巧:
- prototype实现继承
- 条件运算符?:
- 求模运算符%
- ~~
- 使用animate(),改变margin-left值来达到图片移动的效果
效果图:

Demo:
1 function initSlider(container,nav){ 2 this.container = container; 3 this.nav = nav.show(); 4 this.imgs = this.container.find("img"); 5 this.imgWidth = this.imgs[0].width; 6 this.imgLen =this.imgs.length; 7 this.current = 0; 8 } 9 10 //图片移动 11 //改变margin-left值来达到图片移动的效果 12 initSlider.prototype.imgTransition = function(){ 13 this.container.animate({ 14 "margin-left" : -(this.current * this.imgWidth) 15 }) 16 } 17 18 //更新当前current值 19 initSlider.prototype.setCurrent = function(dir){ 20 var pos = this.current; 21 22 //dir==="next" ? ++this.current : --this.current ; 23 //另一种实现方式: 24 pos+= ~~(dir==="next") || -1; 25 26 this.current = (pos<0)? this.imgLen-1 : pos% this.imgLen; 27 return pos 28 }
参考来源:https://tutsplus.com/lesson/prototypal-inheritance-and-refactoring-the-slider/
疑惑之处:关于按位非(~)操作符
~true === -2
~~true === 1
~false === -1
~~false === 0
为什么~true等于-2?为什么 ~false等于-1?
遇到的困难:
对this的指向,糊涂了几次。 --对this不够熟悉
对current值的++,--。犯错了几次。--逻辑思考能力。
收获:
pos+= ~~(dir==="next") || -1;
(pos<0)? this.imgLen-1 : pos% this.imgLen;
写法很帅,很惊喜!
附:另一种实现方式。
没有上面那种方式那样优雅,不过作为学习记录,也记在这里先吧。
1 (function($){ 2 var slider = $("div.slider").css("overflow","hidden").children("ul"), 3 img = $("img"), 4 imgLen = img.length, 5 imgWidth = img[0].width, 6 imgTotal = imgWidth * imgLen, 7 current = 1; 8 $("#slider-nav").show().find("button").on("click",function(){ 9 var direction = $(this).data("dir"), 10 loc = imgWidth; 11 12 ($(this).data("dir")==="next") ? ++current : --current ; //先加减,再取用current 13 14 if(current===0){ 15 current = imgLen; 16 direction = "next"; 17 loc = imgTotal - imgWidth; 18 } 19 else if(current-1 === imgLen){ 20 current = 1 ; 21 loc = 0; 22 } 23 imgTransition(slider,loc,direction); 24 25 }); 26 27 function imgTransition (slider,loc,direction){ 28 var unit; 29 if(direction&&loc!=0) unit =(direction === "next")? "-=":"+="; 30 slider.animate({ 31 "margin-left" : unit?unit+loc:loc 32 }) 33 } 34 35 })(jQuery);
浙公网安备 33010602011771号