이미지 없을때 처리 방법 질문해요
본문
A
B
C
세 이미지가 있는데
A 이미지가 경로상에 있으면
B로 대체, B이미지도 없다면
C 이미지로 대체 하려고 하는데
어떻게 해야할까요...
<img src="A" onerror="this.src=B';"/>
로하면 A에서 B로는 되는데 B가 없다면 C로 가야하는데 방법을 모르겠어요
답변 5
<script>
function img_src_alternatives(img) {
if (img.onerror == null) {
img.onerror = function () {
let src_candidates = this.dataset.srcCandidates.split(',');
src_candidates = src_candidates.map((src) => src.trim());
src_candidates = src_candidates.filter((src) => src.length > 0);
if (src_candidates.length == 0) {
this.onerror = null;
return;
}
this.src = src_candidates.shift();
this.dataset.srcCandidates = src_candidates.toString();
}
}
}
document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('img[data-src-candidates]').forEach((img, idx, arr) => {
img_src_alternatives(img);
});
});
</script>
<img src="A" data-src-candidates="B,C,D,E,F">
<img id="myImage" src="A" onerror="replaceImage(this);">
<script>
function replaceImage(img) {
if (img.src.endsWith("A")) {
img.src = "B";
} else if (img.src.endsWith("B")) {
img.src = "C";
}
}
</script>
<?php
$img = 'https://example.com/a.jpg';
// cURL 사용
$ch = curl_init($img);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
echo "이미지가 존재합니다.";
} else {
echo "이미지가 존재하지 않습니다. HTTP 상태 코드: " . $httpCode;
}
?>
이런식으로 $img1 $img2 $img3 를 미리 변수에 담아놓고 처리할수도 있어요.
!-->
php file_exists 함수를 찾아보시고
파일유무에 따라서 if문으로 처리하면될듯합니다.
<img id="img_1" src="A">
<script>
img_1.onerror = () => {
img_1.id = "img_2";
img_2.src = "B";
img_2.onerror = () => {
img_2.src = "C";
}
}
</script>
그런데 온에러 이벤트는 F12 에서 빨간색이 들어와서
php 에서 file_exists() 등으로 파일존재유무를 파악하는 것이 좋습니다.
자바스크립트에서 이미지파일이 존재하는지 확인하려면 아작스로 이미지url 자체를 땡겨서 404 오류메시지를 뿜어내면 그 이미지가 없는 것으로 판단하는 꼼수도 있긴 합니다.
!-->
답변을 작성하시기 전에 로그인 해주세요.