- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Document</title>
- <style>
- img {
- display: block;
- margin-bottom: 50px;
- width: 400px;
- height: 400px;
- }
- </style>
- </head>
- <body>
- <img src="" data-src="http://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg" alt="">
- <img src="" data-src="http://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg" alt="">
- <img src="" data-src="http://ww1.sinaimg.cn/large/006y8mN6gw1fa7kaed2hpj30sg0l9q54.jpg" alt="">
- <img src="" data-src="http://ww1.sinaimg.cn/large/006y8mN6gw1fa7kaed2hpj30sg0l9q54.jpg" alt="">
- <img src="" data-src="http://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg" alt="">
- <img src="" data-src="http://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg" alt="">
- <img src="" data-src="http://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg" alt="">
- <img src="" data-src="http://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg" alt="">
- <img src="" data-src="http://ww1.sinaimg.cn/large/006y8mN6gw1fa7kaed2hpj30sg0l9q54.jpg" alt="">
- <img src="" data-src="http://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg" alt="">
- <img src="" data-src="http://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg" alt="">
- </body>
-
- <script>
- var num = document.getElementsByTagName('img').length;
- var img = document.getElementsByTagName("img");
- var n = 0; //存儲圖片加載到的位置,,避免每次都從第一張圖片開始遍歷
- lazyload(); //頁面載入完畢加載可是區(qū)域內(nèi)的圖片
- //window.onscroll = lazyload;
- function lazyload() { //監(jiān)聽頁面滾動事件
- var seeHeight = document.documentElement.clientHeight; //可見區(qū)域高度
- var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; //滾動條距離頂部高度
- for (var i = n; i < num; i++) {
- if (img[i].offsetTop < seeHeight + scrollTop) {
- if (img[i].getAttribute("src") == "") {
- img[i].src = img[i].getAttribute("data-src");
- }
- n = i + 1;
- }
- }
- }
-
-
-
- // 簡單的節(jié)流函數(shù)
- //fun 要執(zhí)行的函數(shù)
- //delay 延遲
- //time 在time時間內(nèi)必須執(zhí)行一次
- function throttle(fun, delay, time) {
- var timeout,
- startTime = new Date();
- return function() {
- var context = this,
- args = arguments,
- curTime = new Date();
- clearTimeout(timeout);
- // 如果達到了規(guī)定的觸發(fā)時間間隔,,觸發(fā) handler
- if (curTime - startTime >= time) {
- fun.apply(context, args);
- startTime = curTime;
- // 沒達到觸發(fā)間隔,重新設定定時器
- } else {
- timeout = setTimeout(function(){
- fun.apply(context, args);
- }, delay);
- }
- };
- };
- // 實際想綁定在 scroll 事件上的 handler
- //function lazyload(event) {}
- // 采用了節(jié)流函數(shù)
- window.addEventListener('scroll',throttle(lazyload,500,1000));
-
- </script>
- </html>
|