若遇到图片加载很慢的问题,对这种情况,手机开发一般用canvas方法加载:
具体的canvas API 参见:http://javascript.ruanyifeng.com/htmlapi/canvas.html
下面举例说明一个canvas的例子:
- <li><canvas></canvas></li>
js动态加载图片和li 总共举例17张图片!
- var total=17;
- var zWin=$(window);
- var render=function(){
- var padding=2;
- var winWidth=zWin.width();
- var picWidth=Math.floor((winWidth-padding*3)/4);
- var tmpl ='';
- for (var i=1;i<=totla;i++){
- var p=padding;
- var imgSrc='img/'+i+'.jpg';
- if(i%4==1){
- p=0;
- }
- tmpl +='<li style="width:'+picWidth+'px;height:'+picWidth+'px;padding-left:'+p+'px;padding-top:'+padding+'px;"><canvas id="cvs_'+i+'"></canvas></li>';
- var imageObj = new Image();
- imageObj.index = i;
- imageObj.onload = function(){
- var cvs =$('#cvs_'+this.index)[0].getContext('2d');
- cvs.width = this.width;
- cvs.height=this.height;
- cvs.drawImage(this,0,0);
- }
- imageObj.src=imgSrc;
- }
- }
- render();