php實現圖片延時載入的方法:在到達指定載入圖片位置時,用data-src屬性值替換img的src屬性值即可,如【imgs[i].src = imgs[i].getAttribute('data-src');】。
在到達指定載入圖片位置時,用data-src的屬性值替換img的src的屬性值即可,這個時候img就會去請求資源。
(推薦教學:)
imgs[i].src = imgs[i].getAttribute('data-src');
程式碼實現:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>圖片懶載入</title> <style> img { display: block; width: 100%; height: 300px; margin-bottom: 20px; } </style> </head> <body> <img data-src="./images/1.jpg" alt=""> <img data-src="./images/2.jpg" alt=""> <img data-src="./images/3.jpg" alt=""> <img data-src="./images/4.jpg" alt=""> <img data-src="./images/5.jpg" alt=""> <img data-src="./images/6.jpg" alt=""> <img data-src="./images/7.jpg" alt=""> <img data-src="./images/8.jpg" alt=""> <img data-src="./images/9.jpg" alt=""> <img data-src="./images/10.jpg" alt=""> <img data-src="./images/1.jpg" alt=""> <img data-src="./images/2.jpg" alt=""> </body> <script> var imgs = document.querySelectorAll('img'); //offsetTop是元素與offsetParent的距離,迴圈獲取直到頁面頂部 function getTop(e) { var T = e.offsetTop; while(e = e.offsetParent) { T += e.offsetTop; } return T; } function lazyLoad(imgs) { var H = document.documentElement.clientHeight;//獲取可視區域高度 var S = document.documentElement.scrollTop || document.body.scrollTop; for (var i = 0; i < imgs.length; i++) { if (H + S > getTop(imgs[i])) { imgs[i].src = imgs[i].getAttribute('data-src'); } } } window.onload = window.onscroll = function () { //onscroll()在卷軸捲動的時候觸發 lazyLoad(imgs); } </script> </html>
相關推薦:
以上就是php如何實現圖片延時載入的詳細內容,更多請關注TW511.COM其它相關文章!