[javascript] div 요소의 크기 조정

jQuery에는 resize()-이벤트가 있지만 창에서만 작동합니다.

jQuery(window).resize(function() { /* What ever */ });

이것은 잘 작동합니다! 하지만 이벤트를 div 요소에 추가하고 싶을 때 작동하지 않습니다.

jQuery('div').resize(function() { /* What ever */ });

div 요소의 크기가 변경되면 콜백을 시작하고 싶습니다. 크기 조정 가능한 이벤트를 시작하고 싶지 않습니다. div 요소의 크기가 변경되었는지 확인하는 이벤트입니다.

이를위한 해결책이 있습니까?



답변

DIVresize이벤트를 발생시키지 않으므로 코딩 한 작업을 정확히 수행 할 수는 없지만 DOM 속성 모니터링을 살펴볼 수 있습니다 .

실제로 크기 조정과 같은 작업을하고 있고 이것이 div의 크기를 변경하는 유일한 방법 인 경우 크기 조정 플러그인은 자체 콜백을 구현할 것입니다.


답변

요소의 너비가 변경되었을 때만 트리거에 관심이 있었기 때문에 (높이는 신경 쓰지 않습니다), 보이지 않는 iframe 요소를 사용하여 정확히 수행하는 jquery 이벤트를 만들었습니다.

$.event.special.widthChanged = {
  remove: function() {
      $(this).children('iframe.width-changed').remove();
  },
  add: function () {
      var elm = $(this);
      var iframe = elm.children('iframe.width-changed');
      if (!iframe.length) {
          iframe = $('<iframe/>').addClass('width-changed').prependTo(this);
      }
      var oldWidth = elm.width();
      function elmResized() {
          var width = elm.width();
          if (oldWidth != width) {
              elm.trigger('widthChanged', [width, oldWidth]);
              oldWidth = width;
          }
      }

      var timer = 0;
      var ielm = iframe[0];
      (ielm.contentWindow || ielm).onresize = function() {
          clearTimeout(timer);
          timer = setTimeout(elmResized, 20);
      };
  }
}

다음 CSS가 필요합니다.

iframe.width-changed {
    width: 100%;
    display: block;
    border: 0;
    height: 0;
    margin: 0;
}

당신은 행동 여기에서 볼 수 있습니다 widthChanged 바이올린


답변

// this is a Jquery plugin function that fires an event when the size of an element is changed
// usage: $().sizeChanged(function(){})

(function ($) {

$.fn.sizeChanged = function (handleFunction) {
    var element = this;
    var lastWidth = element.width();
    var lastHeight = element.height();

    setInterval(function () {
        if (lastWidth === element.width()&&lastHeight === element.height())
            return;
        if (typeof (handleFunction) == 'function') {
            handleFunction({ width: lastWidth, height: lastHeight },
                           { width: element.width(), height: element.height() });
            lastWidth = element.width();
            lastHeight = element.height();
        }
    }, 100);


    return element;
};

}(jQuery));


답변

jquery 플러그인 jquery.resize를 만들었습니다. 지원되는 경우 resizeObserver 를 사용하거나 marcj / css-element-queries 스크롤 이벤트를 기반으로하는 솔루션 , setTimeout / setInterval이 없습니다.

당신은 단지

 jQuery('div').on('resize', function() { /* What ever */ });

또는 리사이 저 플러그인으로

jQuery('div').resizer(function() { /* What ever */ });

나는 jQuery 터미널을 위해 이것을 만들고 분리 된 repo 및 npm 패키지로 추출했지만 그 동안 요소가 iframe 내부에 있으면 크기 조정에 문제가 있었기 때문에 숨겨진 iframe으로 전환했습니다. 그에 따라 플러그인을 업데이트 할 수 있습니다. jQuery 터미널 소스 코드 에서 iframe 기반 크기 조정기 플러그인을 볼 수 있습니다 .

편집 : 페이지가 iframe 내부에있을 때 이전 솔루션이 작동하지 않았기 때문에 새 버전은 iframe을 사용하고 창 개체의 크기를 조정합니다.

EDIT2 : 대체가 iframe을 사용하기 때문에 양식 컨트롤이나 이미지와 함께 사용할 수 없으므로 래퍼 요소에 추가해야합니다.

EDIT3 : : 돌연변이 관찰자를 사용 하는 resizeObserver 폴리 필 을 사용하는 더 나은 솔루션 이 있습니다 (resizeObserver가 지원되지 않는 경우). IE에서도 작동합니다. 또한 TypeScript 타이핑도 있습니다.


답변

이것에 대해 :

divH = divW = 0;
jQuery(document).ready(function(){
    divW = jQuery("div").width();
    divH = jQuery("div").height();
});
function checkResize(){
    var w = jQuery("div").width();
    var h = jQuery("div").height();
    if (w != divW || h != divH) {
        /*what ever*/
        divH = h;
        divW = w;
    }
}
jQuery(window).resize(checkResize);
var timer = setInterval(checkResize, 1000);

BTW div에 ID를 추가하고 $ ( “div”)를 $ ( “# yourid”)로 변경하면 더 빠르며 나중에 다른 div를 추가해도 깨지지 않습니다.


답변

기본 JavaScript와 올해 출시 된 jQuery를위한 정말 멋지고 사용하기 쉽고 가벼운 (탐지에 네이티브 브라우저 이벤트 사용) 플러그인이 있습니다. 완벽하게 수행됩니다.

https://github.com/sdecima/javascript-detect-element-resize


답변

창만 지원되지만 플러그인을 사용할 수 있습니다. http://benalman.com/projects/jquery-resize-plugin/