图片预加载可以预先加载好网页所需的图片,在网页需要某一张图片时,无需再从服务器请求图片数据,直接从缓存文件中获取所需的图片。 图片预加载,极大的提升了用户体验!
完整代码贴在了下面,仅供参考!本文预加载只预加载一张图片,每个人都有各自的需求,可以直接复制此处的代码使用,也可以修改后使用!
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
/** *预加载图片(多往后加载出来一张图片) */ //初始化代码 var list = []; var a = parseInt(Math.random()*5), b = parseInt(Math.random()*5); list.push(a, b); // console.log(list.length); var count = 0; var num = parseInt(Math.random()*111); // console.log("click_num/"+num); // console.log("click_list/"+list); // console.log("click_count"+count+'\n---------------------'); // 图片加载函数,图片会在后台默默加载 function load() { var imgObj = new Image(); imgObj.src = "http://say.ganto.xyz/images/"+list[list.length-1]+".jpg"; } $('.box').css("background-image","url(http://say.ganto.xyz/images/"+list[count]+".jpg)"); load(); //点击box $('.box').click(function(){ num = parseInt(Math.random()*111); // console.log("click_num/"+num); list.push(num); // console.log("click_list/"+list); count++; // console.log("click_count"+count+'\n---------------------'); $('.box').css("background-image","url(http://say.ganto.xyz/images/"+list[count]+".jpg)"); load(); }); //设置定时器 setInterval(function(){ num = parseInt(Math.random()*111); // console.log("setInterval_num/"+num); list.push(num); // console.log("setInterval_list/"+list); count++; // console.log("setInterval_count"+count+'------------'); $('.box').css("background-image","url(http://say.ganto.xyz/images/"+list[count]+".jpg)"); load(); },5000);
<div class="box"> <form> <input onkeyup="this.value=this.value.replace(/[^a-z_^0-9]/ig,'');" placeholder="输入快递单号"/> <button type="button">查询</button> </form> </div>
*{ margin: 0; padding: 0; } body{ position: absolute; top: 0; right: 0; bottom: 0; left: 0; min-width: 300px; min-height: 300px; } .box{ width: 100%; height: 100%; background-repeat: no-repeat; background-size: cover; background-position: center; transition: all 2s ease; display: flex; justify-content: center; align-items: center; cursor: pointer; } .box form{ height: 30px; } .box input{ width: 200px; height: 30px; border: 0; outline: none; background: rgba(255, 255, 255, .8); padding: 0 10px; border-radius: 5px; box-sizing: border-box; position: relative; bottom: 1px; } .box button{ display: inline-block; cursor: pointer; width: 50px; height: 30px; border: 0; background: rgba(255, 255, 255, .8); border-radius: 5px; outline: none; } span{ display: inline-block; text-align: center; position: absolute; border-radius: 10px; border: 1px dashed white; bottom: 0; color: white; cursor: move; padding: 10px 20px; }
本文链接:https://heri.ganto.cn/2020/01/15/advance/
本文更新于:2020-09-26 07:57:50
小站声明:如果你需要“转载”、“引用”小站的文章,可以不需要作者同意,请务必标明出处和文章链接。