JQuery: 크기 조정이 완료된 후에만 크기 조정 이벤트를 호출하는 방법은 무엇입니까?
브라우저 창 크기 조정이 완료되면 기능을 호출하려면 어떻게 해야 합니까?
그렇게 하려고 하는데 문제가 있어요.JQuery Rize 이벤트 기능을 사용하고 있습니다.
$(window).resize(function() {
... // how to call only once the browser has FINISHED resizing?
});
그러나 사용자가 수동으로 브라우저 창 크기를 조정하는 경우 이 기능은 계속해서 호출됩니다.즉, 짧은 시간 내에 이 기능을 수십 번 호출할 수도 있습니다.
브라우저 창 크기 조정이 완료되면 크기 조정 기능을 한 번만 호출하려면 어떻게 해야 합니까?
갱신하다
또한 전역 변수를 사용할 필요가 없습니다.
기준 ID를 setInterval 또는 setTimeout에 저장할 수 있습니다.다음과 같은 경우:
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()
다음과 함께
$(window).resize(function() {
clearTimeout($.data(this, 'resizeTimer'));
$.data(this, 'resizeTimer', setTimeout(function() {
//do something
alert("Haven't resized in 200ms!");
}, 200));
});
갱신하다
jQuery의 기본값을 향상시키기 위해 확장자를 작성했습니다.on
(&bind
)-이벤트-handler.지정된 간격 동안 이벤트가 트리거되지 않은 경우 하나 이상의 이벤트에 대한 이벤트 핸들러 기능을 선택한 요소에 연결합니다.이 기능은 이벤트 크기 조정 등 지연 후에만 콜백을 실행하려는 경우에 유용합니다.https://github.com/yckart/jquery.unevent.js
;(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 Handler). 단, 마지막으로 추가 파라미터를 전달할 수 있습니다.
$(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);
});
위의 내용에 덧붙이자면 스크롤 막대가 튀어나오기 때문에 원하지 않는 크기의 이벤트가 발생하는 것이 일반적인데, 이를 방지하기 위한 몇 가지 코드가 있습니다.
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
});
jsfiddle 보기
언더스코어.js에는 이 작업을 위한 몇 가지 좋은 메소드가 있습니다. 그리고 언더스코어를 사용하지 않더라도 이 함수들의 출처를 살펴보세요.예는 다음과 같습니다.
var redraw = function() {'redraw logic here'};
var debouncedRedraw = _.debounce(redraw, 750);
$(window).on('resize', debouncedRedraw);
이것이 제 접근법입니다.
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);
});
});
resize-event-listener는 수신되는 모든 크기 조정 호출을 잡아내고, 각각에 대해 타임아웃 함수를 생성하고 타임아웃 식별자를 다음과 같은 반복 숫자와 함께 저장합니다.'id-'
(배열 키로 사용 가능)에서tos
-배열을 합니다.
타임아웃 트리거가 발생할 때마다, 그것은fn
-기능, 그것은 확인합니다. 그것이 마지막 타임아웃이었는지.tos
array(fn-function은 실행된 모든 타임아웃을 삭제합니다).참이면 (=if(len-1 == 0)
), 크기 조정이 완료되었습니다.
jQuery는 다음을 제공합니다.off
이벤트 처리기 제거 방법
$(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
'it-source' 카테고리의 다른 글
각도 2: 유형 오류: AppComponent@4:44의 [{thing.title}]에서 l_thing0이 정의되지 않았습니다. (0) | 2023.11.07 |
---|---|
Fast Cross-Platform C/C++ 이미지 프로세싱 라이브러리 (0) | 2023.11.02 |
시간 성분이 없는 NSD 날짜 비교 (0) | 2023.11.02 |
Git 분기 및 Rails 마이그레이션 작업 방법 (0) | 2023.11.02 |
실행 중인 모든 도커 컨테이너를 다시 시작하는 명령? (0) | 2023.11.02 |