我在點擊放大影像。我想在影像正下方放置一個標題,但要做到這一點,我必須知道影像放大后的新渲染高度是多少。我不想要影像的“自然高度”。我怎么做?
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();
});
uj5u.com熱心網友回復:
您不需要知道影像的高度即可將標題放在影像的底部。修改您的 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/475389.html
