<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div style="width: 117px;height: 38px;background: red;margin-top: 2000px;margin-bottom: 1000px;">
<img src="" chuli="false" my_src="https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top_86d58ae1.png">
</div>
<script>
function getScrollTop() {
var scroll_top = 0;
if (document.documentElement && document.documentElement.scrollTop) {
scroll_top = document.documentElement.scrollTop;
}
else if (document.body) {
scroll_top = document.body.scrollTop;
}
return scroll_top;
}
let div = document.querySelector("div")
let img = document.querySelector("img")
window.onscroll = function(){
if(img.chuli === "true"){
return
}
var a = getScrollTop()
if((a + document.documentElement.clientHeight) > div.style.marginTop.split("px")[0]){
//此处需要注意的事,dom原生的属性可以直接点出来,但是自定义的点不出来
console.log(img.src)
//需要这样获取和设置
img.src = img.getAttribute("my_src")
img.setAttribute("chuli","true")
div.style.background = "#FFF"
}
}
</script>
</body>
</html>
实现简易的图片懒加载
最新推荐文章于 2024-05-30 17:38:42 发布