原生弹窗,图片宽高自适应
2018-09-30 本文已影响6人
奋斗的小小小兔子
弹窗图片宽高自适应
<div class="modal fade hide" id="modal">
<div class="modal-content">
<div class="close-btn" id="close-btn"></div>
<img src="./images/reward.png" alt="reward" />
</div>
</div>
<script>
window.onload = function () {
const rewardIcon = document.getElementById('reward-icon');
const modal = document.getElementById('modal');
const closeModal = document.getElementById('close-btn');
rewardIcon.addEventListener('click', function () {
modal.classList.remove('hide');
document.body.classList.add('modal-open');
});
closeModal.addEventListener('click', function () {
modal.classList.add('hide');
document.body.classList.remove('modal-open');
})
}
</script>
// 灰色背景
.modal {
position: fixed;
right: 0;
left: 0;
bottom: 0;
top: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}
// 弹窗主内容,白底,宽度固定,高度根据内容自适应
.modal-content {
position: relative;
width: 930px;
height: auto;
padding: 60px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.5);
background: #f9f9f9;
display: flex;
justify-content: center;
align-items: center;
transition: opacity 1s ease-in;
opacity: 1;
visibility: visible;
}
// 关闭按钮,使用雪碧图
.modal .modal-content .close-btn {
position: absolute;
top: -18px;
right: -18px;
background: url("../images/fancybox_sprite@2x.png") no-repeat;
background-size: 44px 152px;
width: 36px;
height: 36px;
cursor: pointer;
}
// 图片内容宽高自适应
.modal .modal-content img {
display: block;
width: auto;
height: auto;
max-width: 100%;
max-height: 100%;
}
.hide {
display: none;
opacity: 0;
visibility: hidden;
}
// 打开弹窗,固定背景,不随页面滚动
.modal-open {
overflow-y: hidden;
}