js图片懒加载插件


<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title> js图片懒加载插件</title>
		
		<style type="text/css">
			img {
				width: auto;
				height: auto;
				margin:5% auto;
			}

			.con {
				width: 40%;
				padding-left: 10%;
				padding-right: 10%;
				position: relative;
				height: auto;
				margin: auto;
				display: flex;
				align-items: center;
				justify-content: space-around;
				flex-direction: row;
				flex-wrap: wrap;
			}

			.test {
				width: 420px;
				height: auto;
				text-align: center;
			}
			.test img{
				width:320px;
				height:320px;
				object-fit: fill;
				margin: auto;
			}
		</style>
	</head>
	<body>
		<h3 style="text-align: center">向下滚动才会加载当前可见图片</h3>
		<div class="con">
			<img _src="https://picsum.photos/id/1/200/300"alt="">
			<img _src="https://picsum.photos/id/2/200/300"alt="">
			<img _src="https://picsum.photos/id/3/200/300"alt="">
			<img _src="https://picsum.photos/id/4/200/300"alt="">
		</div>
		<div class="con test">
			<div class="test">
				<img _src="https://picsum.photos/id/100/200/300"alt="">
				<img _src="https://picsum.photos/id/101/200/300"alt="">
			</div>
			<img _src="https://picsum.photos/id/102/200/300"alt="">
			<img _src="https://picsum.photos/id/103/200/300"alt="">
			
			<img _src="https://picsum.photos/id/104/200/300"alt="">
			<img _src="https://picsum.photos/id/108/200/300"alt="">
			<img _src="https://picsum.photos/id/106/200/300"alt="">
		</div>
	</body>
<script>
function LazyLoad(n, conf) {
	var Agent = navigator.userAgent;
	var isIE = Agent.indexOf("compatible") > -1 && Agent.indexOf("MSIE") > -1;
	if (isIE) {
		window.attachEvent("scroll", Load);
	}
	window.addEventListener("scroll", Load);
	var imgs = document.getElementsByTagName(n);
	var len = imgs.length;
	var an = conf.attr || "_src";
	var th = conf.th || 10;
	var dataList = [];
	var load = document.createElement("style");
	load.innerHTML=".loading{min-width:50px;min-height:50px}";
	for (var i = 0; i < len; i++) {
		dataList.push(imgs[i].getAttribute(an));
		imgs[i].classList.add("loading");
	}
	Load();
	document.documentElement.appendChild(load);

	function Load() {
		var scrollTop = document.documentElement.scrollTop ||
			document.body.scrollTop || window.scrollY;
		for (var i = 0; i < len; i++) {
			var _tNode = imgs[i];
			var top = _tNode.getBoundingClientRect().top || (imgs[i].offsetTop - scrollTop); //
			if (top < window.innerHeight - th && (top > 0)) {
				if (_tNode.src !== 'undefined') {
					_tNode.src = dataList[i];
					_tNode.removeAttribute(an);
					_tNode.classList.remove("loading");
				}
			}
		}
	}
};
</script>
	<script type="text/javascript">
		LazyLoad("img", {
			attr: "_src", //属性名 默认为_src
			th: 100, //该值最好不要超过图片本身高度,否则无法加载
		});
	</script>
</html>


评论 (0)

最新评论(0)
评 论

你来打破零评论

Copyright ©2021 115cms综合内容管理系统 V4.04All Rights Reserved.