0

In developing a navigation menu with very specific design details, I am using this to check the window size and append some code after selected elements.

$(document).ready(function() {
// Optimalisation: Store the references outside the event handler:
var $window = $(window);

function checkWidth() {
    var windowsize = $window.width();
    if (windowsize >= 768) {
        //if the window is greater than 440px wide then turn on jScrollPane..
        $('nav.dropdowns ul.patient>li:nth-child(4n+5)').after('<div class="clear"></div>');
    }
    else if (windowsize <= 767) {
        //if the window is greater than 440px wide then turn on jScrollPane..
        $('nav.dropdowns ul.patient>li:nth-child(3n+4)').after('<div class="clear"></div>');
    }
}
// Execute on load
checkWidth();
// Bind event listener
$(window).resize(checkWidth);
});

The problem is that it keeps firing, which appends my code endlessly. I can easily solve this by removing the event listener. This works great is a window is loaded as it's final size. But in terms of fluid responsiveness, it fails as the event only first on load and not anytime after that. I have looked at a thousand other scripts, but have found no way to prevent the event from firing over and over again that I can actually get working.

4

1 回答 1

0

如果您只想不过度触发该功能,您可以使用setTimeoutand clearTimeout。尝试这样的事情:

$(document).ready(function() {
    // Optimalisation: Store the references outside the event handler:
    var $window = $(window);

    function checkWidth() {
        var windowsize = $window.width();
        if (windowsize >= 768) {
            //if the window is greater than 440px wide then turn on jScrollPane..
            $('nav.dropdowns ul.patient>li:nth-child(4n+5)').after('<div class="clear"></div>');
        }
        else if (windowsize <= 767) {
            //if the window is greater than 440px wide then turn on jScrollPane..
            $('nav.dropdowns ul.patient>li:nth-child(3n+4)').after('<div class="clear"></div>');
        }
    }

    var timeoutId;
    function resizeEvent(){
        // 'reset' the timeout each fire
        clearTimeout(timeoutId);
        // save reference to the timeout delay in 'timeoutId'.  10ms delay
        timeoutId = setTimeout(checkWidth, 10);
    }

    // Execute on load
    checkWidth();
    // Bind event listener
    $(window).resize(resizeEvent);
});

这将持续触发resizeEvent(),但 10ms 延迟将阻止checkWidth()持续运行。

注意:这是您的问题的解决方案,但可能不是最佳解决方案。你应该尽可能多地实现CSS

于 2012-12-14T21:47:44.683 回答