我有一个函数可以根据具有相同类别的其他 div 的高度(以像素为单位)调整 div 的大小:
<script type="text/javascript">
function resizeTheDivs(tag){
// first get the tags to adjust
var $tags = $('.' + tag);
var $new_height = 0;
// find out which one is largest
$('.' + tag).each(function(){
$(this).height() > $new_height ? $new_height = $(this).height() : null;
});
// make all others that height
$tags.height($new_height);
// I console.log($new_height) here sometimes
}
// resize divs on document load
$(document).ready(function(){
resizeTheDivs('the-class');
});
// resize divs on window resize
$(window).resize(function () {
resizeTheDivs('the-class');
});
</script>
div 在页面加载时正确调整大小,但是当 console.log($new_height)
从窗口调整大小函数触发时,$new_height
没有改变。
上下文:有 3 个 div(向左浮动,因此彼此相邻,宽度为 33%)在 p
标签中包含文本。因此,当我调整浏览器宽度时,文本会“变长”,但 javascript 函数不会获取 div 的新高度。
有什么想法吗?
最佳答案
您需要在测量之前将height
重置为auto
,否则它将始终返回您在$(document).ready中设置的固定值
:
function resizeTheDivs(tag){
// first get the tags to adjust
var $tags = $('.' + tag);
var $new_height = 0;
// find out which one is largest
$('.' + tag).each(function(){
$(this).removeAttr('style');
$(this).height() > $new_height ? $new_height = $(this).height() : null;
});
// make all others that height
$tags.height($new_height);
// I console.log($new_height) here sometimes
}
关于javascript - 在窗口调整大小时获取 div 的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41504914/