Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- node-sass #dart-sass
- nginx설치
- 바닐라자바스크립트
- nginx루트경로변경
- 자바스크립트객체배열로
- animation progressbar
- PHP설치
- #push() 함수 #Object.keys()함수 #Object.values()함수 #Object.entries()함수
- 부트스트랩 프로그레스바
- 애니메이션프로그레스바
- 이미지유무체크
- JSON.parse()
- git remote: Permission to .. denied to error: 403 에러
- 바닐라자바스크립트 텍스트 바꾸기
- 버튼클릭하면박스나타남 #버튼클릭시박스노출 #버튼클릭시아래버튼밀어내림
- nginx와php연동
- node-sass #sass #사스
- 빗버킷ssh
- CSS버튼효과
- CSS버튼애니메이션 #버튼클릭하면
- 클릭display:none #클릭하면버튼노출
- PHP에서데이터로그
- JSON.stringify()
- 자바스크립트객체를문자열로
- vanillajs
- 체크박스
Archives
- Today
- Total
●▲■ 개발일기
[javascript] 이미지가 있는지 없는지 체크하여 default이미지 뿌려주는 함수. 본문
이미지가 없는 경우에 예외처리는 보통 img 태그 안에 onerror="this.style.display = 'none'" 처리하면 되는데,
onerror를 사용하지 않고 함수로 처리하는 방법 중 하나를 기록.
html 코드에 적용한 예.
이미지가 없으면 : https://dev-5.onns.co.kr/~sml/pcare-v4/web-www/_lib/img/img-default-drug.png
이미지가 있으면 : https://www.pharm.or.kr:442/images/sb_photo/big3/201802190001101.jpg
<script>
// 이미지가 없는 경우를 체크하기 위해 해당 이미지의 URL을 변수에 저장
const defaultImageUrl = "./img/img-default-drug.png";
// 이미지가 있는지 체크하는 함수
function checkImageExists(imageUrl) {
// 새로운 이미지 객체 생성
const img = new Image();
// 이미지 로드가 성공한 경우
img.onload = function () {
// 이미지가 존재하는 경우 true를 반환
return true;
};
// 이미지 로드가 실패한 경우
img.onerror = function () {
// 이미지가 존재하지 않는 경우 false를 반환
return false;
};
// 이미지 URL 설정
img.src = imageUrl;
// 이미지가 존재하는지 여부를 반환
return img.complete;
}
// 이미지가 없는 경우 defaultImageUrl을 반환하는 함수
function getImageUrl(imageUrl) {
// 이미지가 존재하는 경우 해당 URL을 반환
if (checkImageExists(imageUrl)) {
return imageUrl;
}
// 이미지가 존재하지 않는 경우 defaultImageUrl을 반환
return defaultImageUrl;
}
</script>
<body>
<img id="myImage" src="">
<script>
// 이미지가 있으면 myImage 아이디를 갖고 있는 img 태그에 적용한다.
// 없으면 getImageUrl 함수안에 return defaultImageUrl; 실행.
document.getElementById("myImage").src = getImageUrl("https://www.pharm.or.kr:442/images/sb_photo/big3/201802190001101.jpg");
</script>
</body>
JS영역에서 하단 https://www.pharm.or.kr:442/images/sb_photo/big3/201802190001101.jpg 이미지의 주소를 바꿔서 이미지가 없으면 default 이미지로 바뀌는 것을 확인할 수 있다.
See the Pen 이미지가 있는지 없는지 체크하여 default이미지 뿌려주는 함수. by Lee sangmin (@sangmin2) on CodePen.
'👉 javascript' 카테고리의 다른 글
[javascript] 자바스크립트 객체를 배열로 변환하는 방법 (0) | 2023.05.29 |
---|---|
[javascript] 체크박스 클릭하면 오른쪽 텍스트에 line-through 적용. (0) | 2023.05.28 |
[bootstrap] 부트스트랩 스타일 프로그래스바 progressBar (1) | 2023.02.17 |
[JavaScript] display: none에서 block으로 transition animation의 적용. (0) | 2021.12.30 |
[JavaScript] 비밀번호 정규표현식 유효성 검사 (버튼 활성화) (0) | 2021.12.20 |