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()しますが、10 ミリ秒の遅延により、継続的にcheckWidth()実行することができなくなります。

注:これは問題の解決策ですが、最適な解決策ではない可能性があります。できる限り多くのことを達成することを検討する必要があります。CSS

于 2012-12-14T21:47:44.683 に答える