[英]How to get the height of image inside Bootstrap modal dialog (JS)
This is sorta driving me insane, I have this modal that is scrolling past the window view, but I need to know the height of its content. 这有点让我疯狂,我有这个模式滚动浏览窗口视图,但我需要知道其内容的高度。
Now, my JS gives that their height is 0, so naturally I went and console.log the node object to inspect what's wrong. 现在,我的JS给出了它们的高度为0,所以我自然而然地在console.log节点对象中检查了什么是错误的。
And then... in the browser console, it gives the actual height it should be, but... not if I console.log directly the height attribute. 然后......在浏览器控制台中,它给出了它应该的实际高度,但是......如果我直接控制了.log,请调整高度属性。
So, how can I get the actual height of a div and what is going on here? 那么,我怎样才能得到div的实际高度以及这里发生了什么?
Code: 码:
$('.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
event onload
事件 You should check the offsetHeight
of the image, when the onLoad
event is triggered. 当触发
onLoad
事件时,您应该检查图像的offsetHeight
。
Example : 示例:
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
modal dialog
However, you are using a Bootstrap modal dialog
, wich adjusts automatically its size according to the contents, using an animation. 但是,您正在使用Bootstrap
modal dialog
,它会根据内容使用动画自动调整其大小。 In consequence, until the modal dialog
finishes the animation, you will not be able to get the real image Height. 因此,在
modal dialog
完成动画之前,您将无法获得真实的图像高度。
You should wait for the shown.bs.modal
event . 您应该等待
shown.bs.modal
事件 。
This event is fired when the modal has been made visible to the user (will wait for CSS transitions to complete).
当模态对用户可见时将触发此事件(将等待CSS过渡完成)。
Usage : 用法:
$('.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.