[英]How to get the height of image inside Bootstrap modal dialog (JS)
這有點讓我瘋狂,我有這個模式滾動瀏覽窗口視圖,但我需要知道其內容的高度。
現在,我的JS給出了它們的高度為0,所以我自然而然地在console.log節點對象中檢查了什么是錯誤的。
然后......在瀏覽器控制台中,它給出了它應該的實際高度,但是......如果我直接控制了.log,請調整高度屬性。
那么,我怎樣才能得到div的實際高度以及這里發生了什么?
碼:
$('.modal').modal('toggle'); for (let i = 0; i < 6; i++) { $('.modal-body').append(` <img src="https://i.imgur.com/FcOwQDX.gif"> `) } for (const img of $('.modal-body').children()) { console.log(img, img.offsetHeight); }
<script src="http://code.jquery.com/jquery-3.3.1.slim.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.bundle.min.js"></script> <div class="modal fade" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-body"> </div> </div> </div> </div>
onload
事件 當觸發onLoad
事件時,您應該檢查圖像的offsetHeight
。
示例:
let img = $('<img src="https://i.imgur.com/FcOwQDX.gif">'); img.on('load', function(){ alert( 'offsetHeight : ' + this.offsetHeight+ 'px' ) }); $('.container').append(img)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> </div>
modal dialog
但是,您正在使用Bootstrap modal dialog
,它會根據內容使用動畫自動調整其大小。 因此,在modal dialog
完成動畫之前,您將無法獲得真實的圖像高度。
您應該等待shown.bs.modal
事件 。
當模態對用戶可見時將觸發此事件(將等待CSS過渡完成)。
用法:
$('.modal').on('shown.bs.modal', function (e) {
console.log('modal box resizing complete. Content sizes ready to be checked!')
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.