加载条一直显示0% 图片点击下一页切换不了

来源:2-3 实例1图片相册之使用预加载

夏不语冰

2017-07-14 11:35

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<script src="js/jquery-3.2.1.slim.min.js"></script>
<title>图片之无序加载</title>

<style type="text/css">
html,body{ height:100%;}
	.box{ text-align: center;}
	 a{ text-decoration:none; }	
	.btn{display: inline-block;
		height: 30px;
		line-height: 30px;
		border:  #000000 solid 1px;
		padding: 0 8px;
		background-color: #FFCCCC;
		color:#333333;
	 	margin:0 5px;
	}
	.box a:hover{ background-color:#333333; color: #FFCCCC; }
		.loading{
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		text-align: center;
		background-color: #eee;
		font-size: 30px;
	}
	.progress{
		margin-top: 300px;}
</style>
<script>
	var imgs=[

		'http://i2.hoopchina.com.cn/user/308/15960308/13383588090.jpg',

		'http://img.article.pchome.net/00/44/23/20/pic_lib/wm/2.jpg',

		'http://lcd.yesky.com/imagelist/2009/044/404q4y8g4m0p.jpg',

		'http://lcd.yesky.com/imagelist/2009/044/cgro54wt2t2x.jpg'

	];
	
	var index=0;
	var len=imgs.length;
	var count=0;
	var $progress=$('.progress');


	    $.each(imgs,function(i,src){
	    	var imgObj= new Image();
	    	$(imgObj).on('load error',function(){
	    		$progress.html(Math.round((count+1)/len*100)+'%');
	    		if(count>=len-1){
	    			$('.loading').hide();
	    			document.title='1/'+len;
	    		}
    			count++;
	    	});
	    	imgObj.src=src;
	    });

	$('.btn').on('click', function(){
		if($(this).data('control')==='prev'){
			index=Math.max(0,--index);  //index先减 再与0比较
		}else{		
			index=Math.min(len-1,++index);  //index先加加,与数组的总长度比较		
		}
		document.title=(index+1)+'/'+len;
		$('#img').attr('src',imgs[index]);
	});

</script>
</head>

<body>
<div class="loading">
	<p class="progress">0%</p>
</div>
	<div class="box">
 	  
	  <img src="images/sreen.jpg" alt="phone" id="img" width="900px"/>
   <p>
  	<a href="javascrip:;" data-control="prev" class="btn">上一页</a>
  	<a href="javascrip:;" data-control="next" class="btn">下一页</a>
  </p>
	</div>
 

</body>
</html>


写回答 关注

3回答

  • 韶华_易逝
    2018-09-17 12:22:49

    把你的js代码放到内容代码后面就行了

  • 对酌
    2018-08-29 17:02:07

    关于$progress=$('.progress')         ,   JQ中是支持这种写法的。

  • 妙柴
    2017-07-14 14:40:23

    第52行 var $progress=$('.progress');改为 var progress=$('.progress');

    同理,第58行也要改一改

图片预加载

预知发生的行为,提前加载需要的图片,获得更好的用户体验

40976 学习 · 88 问题

查看课程

相似问题