JS实现图片预加载之无序预加载功能代码
程序员文章站
2022-06-20 08:03:52
图片预加载之无序预加载的效果图如下所示,如果大家感觉不错,请参考实现代码。
具体代码如下所示:
图片预加载之无序预加载的效果图如下所示,如果大家感觉不错,请参考实现代码。
具体代码如下所示:
<!doctype html> <html lang="zh-cn"> <head> <meta charset="utf-8"> <title>preloading</title> <style> *{margin:0; padding:0; border:none; outline:0; text-decoration:none;} html,body,.box{width:100%; height:100%;} .box{display:none;} #img{width:90%; height:90%; margin:2vh auto 0; display:block; box-shadow:0 0 10px gray;} .box .btns{width:140px; height:40px; display:block; margin:20px auto;} .box .btns .btn{width:60px; height:40px; display:block; border:1px gray solid; background-color:#ccc; text-align:center; line-height:40px; float:left;} .box .btns .btn:nth-of-type(2){margin-left:16px;} .load{width:100%; height:100%; display:block; font-size:60px; font-family:"微软雅黑"; color:#ccc; text-align:center; line-height:100vh; position:fixed;} </style> </head> <body> <div class="box"> <img id="img" src="" alt="pic"> <p class="btns"><a href="javascript:" rel="external nofollow" rel="external nofollow" class="btn">prev</a><a href="javascript:" rel="external nofollow" rel="external nofollow" class="btn">next</a></p> </div> <p class="load">0%</p> <script type="text/javascript"> var imgs = ['http://down.699pic.com/photo/50036/7661.jpg?_upt=da51378d1494571758&_upd=500367661.jpg', 'http://desk.fd.zol-img.com.cn/t_s1920x1080c5/g5/m00/09/0f/chmkjljskiqipx9baampyuin8dcaabj8qb7xpyaaw_i343.jpg', 'http://desk.fd.zol-img.com.cn/t_s1920x1080c5/g5/m00/09/0f/chmkjljskleiaw-jaaiudn_yqvgaabj8gdqo5aaai6m64.jpeg', 'http://desk.fd.zol-img.com.cn/t_s1920x1080c5/g5/m00/0f/08/chmkjlauzisih0uxaaruhujlvx8aah8-ghu6zsabfq2166.jpg', 'http://desk.fd.zol-img.com.cn/t_s1920x1080c5/g5/m00/0f/08/chmkjlauzisiil5taaobxg4-xeuaah8-ghzp3eaa5ve000.jpg']; // 绑定按钮事件 var btns = document.getelementsbyclassname('btn'), img = document.getelementbyid('img'), index = 0; for(var i=0;i<btns.length;i++){ btns[i].onclick = function(){ if(this.innerhtml === 'next'){ index = math.min(++index , imgs.length-1); img.setattribute('src',imgs[index]); } if(this.innerhtml === 'prev'){ index = math.max(--index , 0); img.setattribute('src',imgs[index]); } } } // 计数变量 var count = 0, load = document.getelementsbyclassname('load')[0], box = document.getelementsbyclassname('box')[0]; // 无序预加载 for(var i=0;i<imgs.length;i++){ (function(i){ var imgobj = new image(); imgobj.onload = function(){ load.innerhtml = math.round((count + 1) / imgs.length * 100) + '%'; count++; if(count >= imgs.length-1){ load.style.display = 'none'; box.style.display = 'block'; img.setattribute('src',imgs[0]); document.title = '1/' + imgs.length; } } imgobj.onerror = function(){ load.innerhtml = math.round((count + 1) / imgs.length * 100) + '%'; count++; if(count >= imgs.length-1){ load.style.display = 'none'; box.style.display = 'block'; img.setattribute('src',imgs[0]); document.title = '1/' + imgs.length; } } imgobj.src = imgs[i]; })(i); } </script> </body> </html>
以上所述是小编给大家介绍的js实现图片预加载之无序预加载功能代码,希望对大家有所帮助