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

标签 javascript jquery html algorithm

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

相关文章:

javascript - 上传文件 jQuery ajax MVC

jquery - 在 HTML 中找到 Twitter 句柄,然后创建链接

javascript - 如何在 HTML5 Canvas 下保存 iframe 的图像?

javascript -::moment()::jQuery 转换输入值并将其与给定日期进行比较

javascript - 在 JavaScript 中动态加载的绘制到 Canvas 上的图像具有不正确(但接近)的 RGB 值

javascript - 浏览器内 javascript : under what circumstances does window. 打开返回 null/未定义?

javascript - react .js : onClick function from child to parent

php - 使用 AJAX 更新 DOM 以反射(reflect)数据库中的更改的最佳方法是什么?

java - 使用 Play 框架 2.2.x 进行动态自定义验证

javascript - ES6 中的命名对象参数 - 如何检查它们是否已提供?