자바스크립트 모달창 구현

이주영·2024년 4월 12일
0

div > img를 클릭시 pc에선 새창으로 뜨고 모바일 사이즈에선 모달창이 나타나는 퍼블리싱 구현

<html>

<div class="img-attachment">
	<img class="popupImage" src="{{ image.url }}" alt="첨부 이미지"
                         onclick="openWindow(this)">
</div>
<scss>
.img-attachment{
  @include flexStyle(row, flex-start, flex-start);
  flex-wrap: wrap;
  gap: 5px;
  img {
    background:#F7F8FA;
    box-sizing: border-box;
    object-fit: contain;
    @include borderStyle(1px, solid, rgba(0, 0, 0, 0.04), 6px);
    @include ratioStyle(119px, 119px);
    @include mobile{
    @include ratioStyle(64px, 64px);
    }
  }
}
<script>
function openWindow(target){
    var imageUrl = target.getAttribute('src')
    var windowWidth = window.innerWidth;

    if (windowWidth < 749) {
        // 모바일
        openModal(imageUrl);
    } else {
        // PC
        var newWindow = window.open('', '_blank', 'width=800,height=800');
        newWindow.document.write('<html><head><style> body{background-color: #000; display: flex; flex-direction: row; justify-content: center; align-items: center;}img { max-width: 800px; width: auto; min-width: 300px; }</style></head><body><img src="' + imageUrl + '"></body></html>');
    }
}

function openModal(imageUrl) {
    var mbpopupModal = document.getElementById('mbpopupImage');
    var mbpopupImage = document.getElementById('mbmodalImage');

    mbmodalImage.src = imageUrl;
    mbpopupModal.style.display = 'flex';
}

function closeModal() {
    var mbpopupImage = document.getElementById('mbpopupImage');
    mbpopupImage.style.display = 'none';
}
</script>
profile
웹퍼블리셔 주영

0개의 댓글