我正在放大点击图片。我想在图片下面加上一个标题,但要做到这一点,我必须知道图像放大后的新渲染高度是多少。我不想要"自然高度"图像的。我怎么做呢?
html:
<img src="img/img-url.jpg" class="enlarge">
<div class="caption">my caption is here</div>
<div class="popup ">
<img src=""/>
<div class="caption"></div>
</div>
css:
.popup {
position: fixed;
top: 0;
left: 0;
overflow-x: hidden;
z-index: 9999;
width: 100%;
background-color: rgba(0,0,0,.9);
height: 100%;
display: none;
}
.popup img {
max-width: 90%;
max-height: 90%;
position: fixed;
top: 20px;
left: 50%;
transform: translateX(-50%);
-webkit-transform: translateX(-50%);
-moz-transform: translateX(-50%);
-ms-transform: translateX(-50%);
-o-transform: translateX(-50%);
}
.popup .caption {
position: fixed;
width: 100%;
text-align: center;
left: 0;
}
jquery
$('.enlarge').on('click', function(e) {
var thisImg = $(this).attr('src');
var thisCaption = $(this).next().text();
$('.popup img').attr('src', thisImg);
var imgH = $('.popup img').height(); //returns 0 because loads asynchronously
$('.popup .caption').css('top', imgH + 10);
$('.popup .caption').text(thisCaption);
$('.popup').fadeIn();
});
你真的不需要知道图片的高度来把标题放在图片的底部。修改你的css和改变。popup img和标题位置相对。下面是修改后的代码:
$('.enlarge').on('click', function(e) {
var thisImg = $(this).attr('src');
var thisCaption = $(this).next().text();
$('.popup img').attr('src', thisImg);
$('.popup .caption').text(thisCaption);
$('.popup').fadeIn();
});
.popup {
position: fixed;
top: 0;
left: 0;
overflow-x: hidden;
z-index: 9999;
width: 100%;
background-color: rgba(0, 0, 0, .9);
height: 100%;
display: none;
padding-top: 20px;
}
.popup img {
max-width: 90%;
max-height: 90%;
position: relative;
left: 50%;
transform: translateX(-50%);
-webkit-transform: translateX(-50%);
-moz-transform: translateX(-50%);
-ms-transform: translateX(-50%);
-o-transform: translateX(-50%);
}
.popup .caption {
position: relative;
width: 100%;
text-align: center;
left: 0;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://i.stack.imgur.com/HI86p.png" class="enlarge">
<div class="caption">my caption is here</div>
<div class="popup ">
<img src="" />
<div class="caption"></div>
</div>