<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="jquery-1.12.4.min.js"></script> <style> .slide { width:400px; position:relative; overflow:hidden; height:266px; } .slide ul { position:absolute; left:0; top:0; list-style: none; margin:0; padding:0; height:266px; } .slide li { display:inline-block; float:left; } .prev,.next { position:absolute; top:50%; } .prev{ left:10px; } .next { right:0; } </style> </head> <body> <div class="slide"> <ul> <li> <img src="images/01.jpg" /> </li> <li> <img src="images/01.jpg" /> </li> <li> <img src="images/01.jpg" /> </li> <li> <img src="images/01.jpg" /> </li> </ul> <span class="prev">prev</span> <span class="next">next</span> </div> <script type="text/javascript"> var slide = function (obj){ var oSlide = obj; var oSlideUl = oSlide.find("ul"); var oSlideLi = oSlide.find("li"); var w = oSlideLi.width(); oSlideUl.css("width",oSlideLi.length*oSlideLi.width()); var i = 0; //console.log(oSlideLi.length); $(".next").on("click",function(){ i++; if(i>oSlideLi.length-1){ i=0; oSlideUl.animate({ "margin-left":0 },600) }else{ oSlideUl.animate({ "margin-left":-(i*oSlideLi.width()) },600) } console.log(i); }); $(".prev").on("click",function(){ i--; console.log(i); if(i<0){ i=3; oSlideUl.animate({ "margin-left":-(i*oSlideLi.width()) },600) } oSlideUl.animate({ "margin-left":-(i*oSlideLi.width()) },600) console.log(i); }); } slide($(".slide")); </script> </body> </html>
我想问下 为什么有的时候刷新页面获取到的li的宽度为0?
在图片还没加载完的时候得到的宽带就是0了,如果要得到图片加载之后的宽度,建议加一个图片加载的监听,当所有图片加载完之后再取元素宽度
一周热门 更多>