問題:如何知道影像變數已成功從影像 url 加載影像?
我一直在使用的相關 javascript 代碼如下(我正在撰寫 Chrome 擴展程式)。我想從一組影像中抓取隨機影像,以便我可以在網頁上使用(注入)隨機影像。但是由于我從一些擁有大量免費圖片的網站上抓取圖片,我想確保免費圖片網站不會出于任何原因阻止隨機圖片(如果它被阻止,那么我將嘗試另一個隨機圖片也許來自另一個站點)。我需要知道 img.src 是否包含實際影像。我是 javascript 新手,正在閱讀我昨天剛拿到的一本書——我需要分號還是應該放棄使用分號?(我來自 C/C 背景編碼)
const myImages = [];
myImages[0] = 'https://cdn.pixabay.com/photo/2017/02/08/11/09/rainforest-2048447_960_720.jpg';
myImages[1] = 'https://images.freeimages.com/images/large-previews/01a/snail-1397758.jpg';
myImages[2] = 'https://cdn.pixabay.com/photo/2017/09/17/20/35/sloth-2759724_960_720.jpg';
const img = document.createElement('img');
img.src = myImages[Math.floor(Math.random()*myImages.length)];
img.style.width = '100%';
img.style.height = 'auto';
document.querySelector('#pageContent').replaceWith(img);
uj5u.com熱心網友回復:
您可以使用下面的代碼
function checkExist() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("exist")
}
};
xhttp.open("GET",
"https://cdn.pixabay.com/photo/2017/02/08/11/09/rainforest-2048447_960_720.jpg",true);
xhttp.send();
}
uj5u.com熱心網友回復:
如果影像加載錯誤時未加載影像,您應該撰寫邏輯。
const myImages = [];
myImages[0] = 'https://cdn.pixabay.com/photo/2017/02/08/11/09/rainforest-2048447_960_720.jpg';
myImages[1] = 'https://images.freeimages.com/images/large-previews/01a/snail-1397758.jpg';
myImages[2] = 'https://cdn.pixabay.com/photo/2017/09/17/20/35/sloth-2759724_960_720.jpg';
const img = document.createElement('img');
img.src = myImages[Math.floor(Math.random()*myImages.length)];
img.style.width = '100%';
img.style.height = 'auto';
document.querySelector('#pageContent').replaceWith(img);
img.onerror = function() {
// If image not loaded, write your logic here
};
<div id="pageContent">imaged</div>
uj5u.com熱心網友回復:
要驗證您的變數,請使用complete 屬性。
const myImages = [];
myImages[0] = 'https://cdn.pixabay.com/photo/2017/02/08/11/09/rainforest-2048447_960_720.jpg';
myImages[1] = 'https://images.freeimages.com/images/large-previews/01a/snail-1397758.jpg';
myImages[2] = 'https://cdn.pixabay.com/photo/2017/09/17/20/35/sloth-2759724_960_720.jpg';
const img = document.createElement('img');
img.src = myImages[Math.floor(Math.random()*myImages.length)];
img.style.width = '100%';
img.style.height = 'auto';
img.onerror = function() {
// If image not loaded, write your logic here
};
// complete attribute would be false because the image is not yet loaded.
console.log(img.complete);
img.addEventListener("load", () => {
// complete attribute would be true
console.log(img.complete);
document.querySelector('#pageContent').replaceWith(img);
})
uj5u.com熱心網友回復:
嘗試使用 es6 模板文字,而不是模板文字使用帶有屬性的 img 標簽:
var img = `<img src=${myImages.Math.floor(Math.random()*myImages.length)} width='100%' height='auto'`
document.querySelector('#pageContent').appendChield(img);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/365896.html
標籤:javascript 数组 验证
