0
如何跟蹤背景圖片加載進度?我正在關注this article,並在下面寫下這段代碼。使用javaScript加載背景圖片的進度軌跡
var progressbar = document.querySelector('#imgload');
var img = document.createElement('img');
img.onloadstart = function(){
\t progressbar.innerHTML=0;
};
img.onload = function(){
document.body.style.backgroundImage='url("High-Res-Wallpaper-HD-For-Desktop.jpg")';
\t // img.parentElement.removeChild(img);
};
img.onprogress = function(e){
\t if(e.lengthComputable){
\t \t progressbar.innerHTML = e.loaded/e.total * 100;
\t }
};
img.onloadend = function(){
\t progressbar.innerHTML=100;
};
img.src = 'High-Res-Wallpaper-HD-For-Desktop.jpg';
.container{
margin: 0 auto;
width: 900px;
}
<!DOCTYPE html>
<html>
<head>
\t <title>Background image load progress</title>
</head>
<body>
\t <div class="container">
\t <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
\t tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
\t quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
\t consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
\t cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
\t proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
\t </div>
\t <div class='progress'>
\t \t percentage of image load : <span id='imgload'> </span>
\t </div>
</body>
</html>
但它不能正常工作。進度應顯示圖像加載期間的進度值。任何人都可以給我一些想法如何做到這一點?
你是什麼意思_「它不能正常工作」_? – Rayon
'img'元素永遠不會附加到'DOM',你怎麼能刪除它? – Rayon
@Rayon我試圖防止內存泄漏。讓我修正這條線。 –