gpt4 book ai didi

javascript - 在窗口调整大小时获取 div 的高度

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:15:36 24 4
gpt4 key购买 nike

我有一个函数可以根据具有相同类别的其他 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com