Programming

JQuery : 크기 조정이 끝나면 RESIZE 이벤트를 호출하는 방법은 무엇입니까?

procodes 2020. 8. 3. 09:02
반응형

JQuery : 크기 조정이 끝나면 RESIZE 이벤트를 호출하는 방법은 무엇입니까?


브라우저 창의 크기가 조정되면 함수를 어떻게 호출합니까?

나는 그렇게하려고 노력하고 있지만 문제가 있습니다. JQuery Resize 이벤트 함수를 사용하고 있습니다.

$(window).resize(function() {
  ... // how to call only once the browser has FINISHED resizing?
});

그러나이 기능은 사용자가 브라우저 창의 크기를 수동으로 조정하는 경우 계속 호출 됩니다 . 즉,이 함수를 짧은 시간 간격으로 수십 번 호출 할 수 있습니다.

어떻게 난 단지 크기 조정 함수를 호출 할 수있는 하나의 시간 (브라우저 창은 완성 된 크기 조정이되면)?

최신 정보

또한 전역 변수를 사용할 필요가 없습니다.


다음은 jh의 지침을 사용하는 예입니다.

setInterval 또는 setTimeout에 대한 참조 ID를 저장할 수 있습니다. 이처럼 :

var loop = setInterval(func, 30);

// some time later clear the interval
clearInterval(loop);

디 바운스 .

function debouncer( func , timeout ) {
   var timeoutID , timeout = timeout || 200;
   return function () {
      var scope = this , args = arguments;
      clearTimeout( timeoutID );
      timeoutID = setTimeout( function () {
          func.apply( scope , Array.prototype.slice.call( args ) );
      } , timeout );
   }
}


$( window ).resize( debouncer( function ( e ) {
    // do stuff 
} ) );

이 방법은 디 바운스하려는 모든 항목 (핵심 이벤트 등)에 사용할 수 있습니다.

최적의 원하는 효과를 위해 타임 아웃 파라미터를 조정하십시오.


당신은 사용할 수 있습니다 setTimeout()clearTimeout()와 함께 jQuery.data:

$(window).resize(function() {
    clearTimeout($.data(this, 'resizeTimer'));
    $.data(this, 'resizeTimer', setTimeout(function() {
        //do something
        alert("Haven't resized in 200ms!");
    }, 200));
});

최신 정보

jQuery의 기본 (& ) 이벤트 핸들러 를 향상시키는 확장 기능작성했습니다 . 지정된 간격 동안 이벤트가 트리거되지 않은 경우 하나 이상의 이벤트에 대한 이벤트 핸들러 기능을 선택된 요소에 첨부합니다. resize 이벤트와 같이 지연된 후에 만 ​​콜백을 실행하려는 경우에 유용합니다. https://github.com/yckart/jquery.unevent.jsonbind

;(function ($) {
    var methods = { on: $.fn.on, bind: $.fn.bind };
    $.each(methods, function(k){
        $.fn[k] = function () {
            var args = [].slice.call(arguments),
                delay = args.pop(),
                fn = args.pop(),
                timer;

            args.push(function () {
                var self = this,
                    arg = arguments;
                clearTimeout(timer);
                timer = setTimeout(function(){
                    fn.apply(self, [].slice.call(arg));
                }, delay);
            });

            return methods[k].apply(this, isNaN(delay) ? arguments : args);
        };
    });
}(jQuery));

추가 매개 변수를 마지막으로 전달할 수 있다는 점을 제외하고 다른 on또는 bind-event 핸들러 와 같이 사용하십시오 .

$(window).on('resize', function(e) {
    console.log(e.type + '-event was 200ms not triggered');
}, 200);

http://jsfiddle.net/ARTsinn/EqqHx/


var lightbox_resize = false;
$(window).resize(function() {
    console.log(true);
    if (lightbox_resize)
        clearTimeout(lightbox_resize);
    lightbox_resize = setTimeout(function() {
        console.log('resize');
    }, 500);
});

Just to add to the above, it is common to get unwanted resize events because of scroll bars popping in and out, here is some code to avoid that:

function registerResize(f) {
    $(window).resize(function() {
        clearTimeout(this.resizeTimeout);
        this.resizeTimeout = setTimeout(function() {
            var oldOverflow = document.body.style.overflow;
            document.body.style.overflow = "hidden";
            var currHeight = $(window).height(),
                currWidth = $(window).width();
            document.body.style.overflow = oldOverflow;

            var prevUndefined = (typeof this.prevHeight === 'undefined' || typeof this.prevWidth === 'undefined');
            if (prevUndefined || this.prevHeight !== currHeight || this.prevWidth !== currWidth) {
                //console.log('Window size ' + (prevUndefined ? '' : this.prevHeight + "," + this.prevWidth) + " -> " + currHeight + "," + currWidth);
                this.prevHeight = currHeight;
                this.prevWidth = currWidth;

                f(currHeight, currWidth);
            }
        }, 200);
    });
    $(window).resize(); // initialize
}

registerResize(function(height, width) {
    // this will be called only once per resize regardless of scrollbars changes
});

see jsfiddle


Underscore.js has a couple of great methods for this task: throttle and debounce. Even if you're not using Underscore, take a look at the source of these functions. Here's an example:

var redraw = function() {'redraw logic here'};
var debouncedRedraw = _.debounce(redraw, 750);
$(window).on('resize', debouncedRedraw);

This is my approach:

document.addEventListener('DOMContentLoaded', function(){
    var tos = {};
    var idi = 0;
    var fn  = function(id)
    {
        var len = Object.keys(tos).length;

        if(len == 0)
            return;

        to = tos[id];
        delete tos[id];

        if(len-1 == 0)
            console.log('Resize finished trigger');
    };

    window.addEventListener('resize', function(){
        idi++;
        var id = 'id-'+idi;
        tos[id] = window.setTimeout(function(){fn(id)}, 500);
    });
});

The resize-event-listener catches all incoming resize calls, creates a timeout-function for each and saves the timeout-identifier along with an iterating number prepended by 'id-' (to be usable as array key) in the tos-array.

each time, the timout triggers, it calls the fn-function, that checks, if that was the last timeout in the tos array (the fn-function deletes every executed timout). if true (= if(len-1 == 0)), the resizing is finished.


jQuery provides an off method to remove event handler

$(window).resize(function(){
    if(magic == true) {
        $(window).off('resize', arguments.callee);
    }
});

참고URL : https://stackoverflow.com/questions/4298612/jquery-how-to-call-resize-event-only-once-its-finished-resizing

반응형