development

jQuery를 사용하여 div의 높이가 변경되는 경우 감지

big-blog 2020. 6. 21. 19:07
반응형

jQuery를 사용하여 div의 높이가 변경되는 경우 감지


동적으로 추가 및 제거되는 일부 콘텐츠가 포함 된 div가 있으므로 높이가 자주 변경됩니다. 또한 자바 스크립트로 직접 바로 아래에있는 div가 있으므로 div의 높이가 변경되는 시점을 감지 할 수 없으면 div를 그 아래로 재배치 할 수 없습니다.

그렇다면 해당 div의 높이가 언제 변하는 지 어떻게 알 수 있습니까? 사용해야 할 jQuery 이벤트가 있다고 가정하지만 어느 것을 연결해야하는지 잘 모르겠습니다.


css-element-queries 라이브러리의 크기 조정 센서를 사용하십시오.

https://github.com/marcj/css-element-queries

new ResizeSensor(jQuery('#myElement'), function() {
    console.log('myelement has been resized');
});

이벤트 기반 접근 방식을 사용하며 CPU 시간을 낭비하지 않습니다. 모든 브라우저에서 작동 IE7 +.


attrchange 리스너를 위해 플러그인을 작성 했는데 기본적으로 속성 변경에 리스너 기능을 추가했습니다. 플러그인이라고 말하지만 실제로는 jQuery 플러그인으로 작성된 간단한 기능입니다. 원하는 경우 플러그인 특정 코드를 제거하고 핵심 기능을 사용하십시오.

참고 :이 코드는 폴링을 사용하지 않습니다

이 간단한 데모를 확인하십시오 http://jsfiddle.net/aD49d/

$(function () {
    var prevHeight = $('#test').height();
    $('#test').attrchange({
        callback: function (e) {
            var curHeight = $(this).height();            
            if (prevHeight !== curHeight) {
               $('#logger').text('height changed from ' + prevHeight + ' to ' + curHeight);

                prevHeight = curHeight;
            }            
        }
    }).resizable();
});

플러그인 페이지 : http://meetselva.github.io/attrchange/

축소 버전 : (1.68kb)

(function(e){function t(){var e=document.createElement("p");var t=false;if(e.addEventListener)e.addEventListener("DOMAttrModified",function(){t=true},false);else if(e.attachEvent)e.attachEvent("onDOMAttrModified",function(){t=true});else return false;e.setAttribute("id","target");return t}function n(t,n){if(t){var r=this.data("attr-old-value");if(n.attributeName.indexOf("style")>=0){if(!r["style"])r["style"]={};var i=n.attributeName.split(".");n.attributeName=i[0];n.oldValue=r["style"][i[1]];n.newValue=i[1]+":"+this.prop("style")[e.camelCase(i[1])];r["style"][i[1]]=n.newValue}else{n.oldValue=r[n.attributeName];n.newValue=this.attr(n.attributeName);r[n.attributeName]=n.newValue}this.data("attr-old-value",r)}}var r=window.MutationObserver||window.WebKitMutationObserver;e.fn.attrchange=function(i){var s={trackValues:false,callback:e.noop};if(typeof i==="function"){s.callback=i}else{e.extend(s,i)}if(s.trackValues){e(this).each(function(t,n){var r={};for(var i,t=0,s=n.attributes,o=s.length;t<o;t++){i=s.item(t);r[i.nodeName]=i.value}e(this).data("attr-old-value",r)})}if(r){var o={subtree:false,attributes:true,attributeOldValue:s.trackValues};var u=new r(function(t){t.forEach(function(t){var n=t.target;if(s.trackValues){t.newValue=e(n).attr(t.attributeName)}s.callback.call(n,t)})});return this.each(function(){u.observe(this,o)})}else if(t()){return this.on("DOMAttrModified",function(e){if(e.originalEvent)e=e.originalEvent;e.attributeName=e.attrName;e.oldValue=e.prevValue;s.callback.call(this,e)})}else if("onpropertychange"in document.body){return this.on("propertychange",function(t){t.attributeName=window.event.propertyName;n.call(e(this),s.trackValues,t);s.callback.call(this,t)})}return this}})(jQuery)

DOMSubtreeModified 이벤트를 사용할 수 있습니다

$(something).bind('DOMSubtreeModified' ...

그러나 치수가 변경되지 않더라도 발사되며, 발사 될 때마다 위치를 재 할당하면 성능이 저하 될 수 있습니다. 이 방법을 사용한 경험에서 치수가 변경되었는지 확인하는 것이 저렴하므로 두 가지를 결합하는 것이 좋습니다.

또는 div를 contentEditable과 같이 예측할 수없는 방식으로 사용자 입력으로 변경하지 않고 div를 직접 변경하는 경우 언제든지 사용자 정의 이벤트를 발생시킬 수 있습니다.

단점 : IE와 Opera는이 이벤트를 구현하지 않습니다.


이것이 내가이 문제를 최근에 처리 한 방법입니다.

$('#your-resizing-div').bind('getheight', function() {
    $('#your-resizing-div').height();
});

function your_function_to_load_content() {
    /*whatever your thing does*/
    $('#your-resizing-div').trigger('getheight');
}

나는 파티에 몇 년 늦었다는 것을 알고 있습니다. 플러그인을 다운로드하지 않고도 내 대답이 미래에 일부 사람들을 도울 수 있다고 생각합니다.


MutationObserver수업 을 사용할 수 있습니다 .

MutationObserver개발자에게 DOM의 변경 사항에 대응할 수있는 방법을 제공합니다. DOM3 이벤트 사양에 정의 된 돌연변이 이벤트를 대체하도록 설계되었습니다.

( 출처 )

// select the target node
var target = document.querySelector('#some-id');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });    
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);

// later, you can stop observing
observer.disconnect();

이것을 잘 처리 할 수있는 jQuery 플러그인이 있습니다.

http://www.jqui.net/jquery-projects/jquery-mutate-official/

빨간색 테두리가있는 div의 크기를 조정하면 높이가 변경되는 시점에 대한 다양한 시나리오가있는 데모가 있습니다.

http://www.jqui.net/demo/mutate/


user007 님의 질문에 답변 :

항목을 사용하여 추가 된 요소로 인해 요소의 높이가 .append()변경되는 경우 높이의 변화를 감지 할 필요가 없습니다. 새 내용을 첫 번째 요소에 추가 할 때와 동일한 기능으로 두 번째 요소의 위치를 ​​변경하기 만하면됩니다.

에서처럼 :

작업 예

$('.class1').click(function () {
    $('.class1').append("<div class='newClass'><h1>This is some content</h1></div>");
    $('.class2').css('top', $('.class1').offset().top + $('.class1').outerHeight());
});

간단한 setInterval을 만들 수 있습니다.

function someJsClass()
{
  var _resizeInterval = null;
  var _lastHeight = 0;
  var _lastWidth = 0;
  
  this.Initialize = function(){
    var _resizeInterval = setInterval(_resizeIntervalTick, 200);
  };
  
  this.Stop = function(){
    if(_resizeInterval != null)
      clearInterval(_resizeInterval);
  };
  
  var _resizeIntervalTick = function () {
    if ($(yourDiv).width() != _lastWidth || $(yourDiv).height() != _lastHeight) {
      _lastWidth = $(contentBox).width();
      _lastHeight = $(contentBox).height();
      DoWhatYouWantWhenTheSizeChange();
    }
  };
}

var class = new someJsClass();
class.Initialize();

편집하다:

This is a example with a class. But you can do something easiest.


You can use this, but it only supports Firefox and Chrome.

$(element).bind('DOMSubtreeModified', function () {
  var $this = this;
  var updateHeight = function () {
    var Height = $($this).height();
    console.log(Height);
  };
  setTimeout(updateHeight, 2000);
});


Pretty basic but works:

function dynamicHeight() {
    var height = jQuery('').height();
    jQuery('.edito-wrapper').css('height', editoHeight);
}
editoHeightSize();

jQuery(window).resize(function () {
    editoHeightSize();
});

참고URL : https://stackoverflow.com/questions/172821/detecting-when-a-divs-height-changes-using-jquery

반응형