복붙노트

[JQUERY] 사업부의 높이가 jQuery를 사용하여 변경할 때 검출

JQUERY

사업부의 높이가 jQuery를 사용하여 변경할 때 검출

해결법


  1. 1.CSS의 요소 - 쿼리 라이브러리에서 크기 조절 센서를 사용합니다 :

    CSS의 요소 - 쿼리 라이브러리에서 크기 조절 센서를 사용합니다 :

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

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

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


  2. 2.나는 언젠가 다시 기본적으로 속성 변경에 리스너 함수를 추가 attrchange 청취자를위한 플러그인을 썼다. 내가 플러그인으로 말하더라도, 실제로는 ... 플러그인 선택은 특정 코드 전원 스트립을 원하고 핵심 기능을 사용하므로 경우에 .. jQuery 플러그인로 작성된 간단한 기능입니다.

    나는 언젠가 다시 기본적으로 속성 변경에 리스너 함수를 추가 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)
    

  3. 3.당신은 DOMSubtreeModified 이벤트를 사용할 수 있습니다

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

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

    하지만이 경우에도 크기가 변경되지 않는 경우에 발생하고, 화재가 성능 저하를 취할 수 있습니다 때마다 위치를 재 할당됩니다. 내 경험으로는,이 방법을 사용하여 치수 변경 여부 확인에 저렴하고 그래서 당신은 두 가지를 결합하는 것이 좋습니다.

    직접 DIV 변경하는 경우 그렇게 할 때마다, 당신은 단순히 사용자 정의 이벤트가 발생하거나 (대신 사업부를 그것의 contentEditable 경우처럼 예측할 수없는 방법으로 사용자의 입력에 의해 변경되는).

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


  4. 4.나는 최근에이 문제를 처리하는 방법이다 :

    나는 최근에이 문제를 처리하는 방법이다 :

    $('#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');
    }
    

    난 그냥 내 대답은 어떤 플러그인을 다운로드하지 않고, 미래의 어떤 사람들을 도울 수 있다고 생각 나는 파티에 늦게 몇 년이야 ​​알고있다.


  5. 5.당신은 MutationObserver 클래스를 사용할 수 있습니다.

    당신은 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();
    

  6. 6.아주 잘 처리 할 수있는 플러그인 JQuery와가

    아주 잘 처리 할 수있는 플러그인 JQuery와가

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

    여기에 다른 시나리오와 그것의 데모 때와 같다 높이 변화, 당신은 빨간색 테두리 DIV의 크기를 조정합니다.

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


  7. 7.user007 님의 질문에 답변

    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());
    });
    

  8. 8.당신은 간단한 setInterval을 만들 수 있습니다.

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

    someJsClass 함수 () { VAR _resizeInterval = NULL; VAR _lastHeight = 0; VAR _lastWidth = 0; this.Initialize = 함수 () { VAR _resizeInterval =하여 setInterval (_resizeIntervalTick, 200); }; this.Stop = 함수 () { 경우 (_resizeInterval! = null이) 됨 clearInterval (_resizeInterval); }; VAR _resizeIntervalTick = 함수 () { 경우 ($ (yourDiv) .width ()! = _lastWidth || $ (yourDiv) .height의 ()! = _lastHeight) { _lastWidth = $ (contentBox) .width (); _lastHeight = $ (contentBox) .height의 (); DoWhatYouWantWhenTheSizeChange (); } }; } VAR 클래스는 새로운 someJsClass을 () =; class.Initialize ();

    편집하다:

    이 클래스와 예이다. 하지만 당신은 뭔가 쉬운 할 수 있습니다.


  9. 9.당신은이를 사용할 수 있지만 그것은 단지 파이어 폭스와 크롬을 지원합니다.

    당신은이를 사용할 수 있지만 그것은 단지 파이어 폭스와 크롬을 지원합니다.

    $ (요소) .bind ( 'DOMSubtreeModified'함수 () { VAR는이 = $; VAR updateHeight = 함수 () { VAR 높이 = $ ($이) .height의 (); CONSOLE.LOG (높이); }; 에서는 setTimeout (updateHeight, 2000); });


  10. 10.아주 기본적이지만 작동합니다 :

    아주 기본적이지만 작동합니다 :

    function dynamicHeight() {
        var height = jQuery('').height();
        jQuery('.edito-wrapper').css('height', editoHeight);
    }
    editoHeightSize();
    
    jQuery(window).resize(function () {
        editoHeightSize();
    });
    
  11. from https://stackoverflow.com/questions/172821/detecting-when-a-divs-height-changes-using-jquery by cc-by-sa and MIT license