【问题标题】:How can I overwrite my array on window resize?如何在窗口调整大小时覆盖我的数组?
【发布时间】:2016-02-21 08:14:30
【问题描述】:

我有多个具有不同内容和相同类的 div

<div class="my-div"> ... some content here ... </div>
<div class="my-div"> ... some content here ... </div>
<div class="my-div"> ... some content here ... </div>
<div class="my-div"> ... some content here ... </div>
<div class="my-div"> ... some content here ... </div>

现在我将每个单独的高度推入一个数组

var myArray = new Array();

function pushToArray(height) {
    myArray.push(height);
}

function getHeight() {
    $('.my-div').each(function () {
        pushToArray($(this).height());
    });
}

这将返回加载文档时的每个单独高度。如果我知道在窗口重新调整大小时调用此函数链,它将扩展我的数组。我想要的是它用新的高度替换现有的值。

我如何做到这一点?

【问题讨论】:

    标签: javascript jquery html css arrays


    【解决方案1】:

    getHeight函数中重置数组。

    var myArray = [];
    
    function pushToArray(height) {
        myArray.push(height);
    }
    
    function getHeight() {
        // Reinitialize the array
        myArray = [];
    
        $('.my-div').each(function () {
            pushToArray($(this).height());
        });
    }
    
    // Call getHeight on window resize
    $(window).resize(getHeight);
    

    【讨论】:

    • 天哪,我本可以自己搞定的 -.- 谢谢,很有魅力
    • @SlimMarten 欢迎您。很高兴为您提供帮助
    【解决方案2】:

    您可以使用.map()创建数组并结合resize事件使用:

    var array;
    $(window).resize(function(){
        array = $('.my-div').map(function(){
            return $(this).height();
        }).get();
    }).resize();
    

    【讨论】:

      猜你喜欢
      • 2013-10-12
      • 2014-01-01
      • 1970-01-01
      • 2023-03-24
      • 2020-02-02
      • 2015-05-23
      • 2011-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多