$(window).resize() not working

烂漫一生 提交于 2019-12-08 02:16:07

问题


I have the following jquery code to resize a set of elements so that they are all the same height of the tallest element. The function works fine when i refresh the screen, but the $(window).resize() doesn't seem to work.

jQuery(document).ready(function($) {

    function equal_height(target) {
        var maxHeight = -1;

        $(target).each(function() {
            maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
        });

        $(target).each(function() {
            $(this).height(maxHeight);
        }); 
    };

    var responsive_viewport = $(window).width();

    if (responsive_viewport >= 768) {

        equal_height('.cta-text');

        $(window).resize(function() {
            equal_height('.cta-text');
        });
    }

});

回答1:


Worked it out!

The problem isn't how or when the function is called, it's not working because it's basing the new size on the size that was set the first time the function was run.

I've added this to the start of the equal_height function, to reset the height of the element to it's natural height.

$(target).each(function() { 
    $(this).height('auto');
}); 



回答2:


I would consider refactoring to separate out your functions and events. Also you are checking the window on document ready, at which point the window object hasn't loaded anything yet (the DOM is ready before the the window renders). Try this:

jQuery(window).load(function($) {

    var responsive_viewport = $(window).width();

    if (responsive_viewport >= 768) {
        equal_height('.cta-text');

        $(window).resize(function() {
            equal_height('.cta-text');
        });
    }

});


function equal_height(target) {
    var maxHeight = -1;

    $(target).each(function() {
        maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
    });

    $(target).each(function() {
        $(this).height(maxHeight);
    }); 
};

I should also mention that because your resize function is within a conditional statement, it will only fire when the viewport is above 768 pixels — so make sure that you are taking that into account while debugging.




回答3:


Use $(window).resize(function(){}); to trigger events on resize. It only works when you refresh because you're currently not telling it to run anything on resize, but rather when the document fully loads and is ready.



来源:https://stackoverflow.com/questions/22947287/window-resize-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!