初始化项目
This commit is contained in:
63
UI/Scripts/loadImage.js
Normal file
63
UI/Scripts/loadImage.js
Normal file
@@ -0,0 +1,63 @@
|
||||
// onload是等所有的资源文件加载完毕以后再绑定事件
|
||||
window.onload = function () {
|
||||
|
||||
//// 获取图片列表,即img标签列表
|
||||
var imgs = document.querySelectorAll('img');
|
||||
function getTop(e) {
|
||||
return e.offsetTop;
|
||||
}
|
||||
// 懒加载实现
|
||||
function lazyload(imgs) {
|
||||
imgs = document.querySelectorAll('img');
|
||||
for (let i of imgs) {
|
||||
if ($(i).is(':visible') == true) {
|
||||
let trueSrc = i.getAttribute("data-src");
|
||||
|
||||
if (trueSrc != 'null' && trueSrc != null && trueSrc.indexOf('{{') < 0 && trueSrc.indexOf('}}') < 0) {
|
||||
$(i).removeAttr("data-src")
|
||||
//$.ajax({
|
||||
// timeout: 2000,
|
||||
// url: trueSrc,
|
||||
// type: "get",
|
||||
// success: function (data) {
|
||||
// i.setAttribute("src", data);
|
||||
// }
|
||||
//})
|
||||
}
|
||||
//if (trueSrc != 'null' && trueSrc != null && trueSrc.indexOf('{{') < 0 && trueSrc.indexOf('}}') < 0) {
|
||||
// $(i).removeAttr("data-src")
|
||||
// i.setAttribute("src", trueSrc);
|
||||
//}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
return;
|
||||
|
||||
|
||||
// 可视区域高度
|
||||
var h = window.innerHeight;
|
||||
//滚动区域高度
|
||||
var s = document.documentElement.scrollTop || document.body.scrollTop;
|
||||
for (let i of imgs) {
|
||||
//图片距离顶部的距离大于可视区域和滚动区域之和时懒加载
|
||||
//计算方式和第一种方式不同
|
||||
if (i.getBoundingClientRect().top < window.innerHeight) {
|
||||
let trueSrc = i.getAttribute("data-src");
|
||||
if (trueSrc != 'null' && trueSrc != null && trueSrc.indexOf('{{') < 0 && trueSrc.indexOf('}}') < 0) {
|
||||
$(i).removeAttr("data-src")
|
||||
i.setAttribute("src", trueSrc);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
setTimeout(lazyload(imgs), 20);
|
||||
|
||||
// 滚屏函数
|
||||
window.onscroll = function () {
|
||||
//保证每次取到的为最新的
|
||||
lazyload(imgs);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user