老师这样可以吗?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div></div>
<script>
const imgSrc = [
'http://img1.sycdn.imooc.com/climg//5b16558d00011ed506000338.jpg',
'http://img1.sycdn.imooc.com/climg//5b165603000146ca06000338.jpg',
'http://img1.sycdn.imooc.com/climg//5b1656140001c89906000338.jpg']
const londImg = url => {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
resolve(img)
};
img.onerror = () => {
reject(new Error(`Counld not load image at${url.src}`))
};
img.src = url;
})
};
const div = document.querySelector('div');
for (let i = 0; i < imgSrc.length; i++) {
londImg(imgSrc[i])
.then(url => {
setTimeout(() => {
div.appendChild(url)
}, (i + 1) * 1000)
});
};
</script>
</body>
</html>
19
收起
正在回答
2回答
同学你好,这样写效果是对的,建议优化一下实现方案:
londImg返回的是promise对象,所以可以通过链式调用(不用循环),实现逐一加载出图片,如下:
解释说明:
祝学习愉快!
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星