복붙노트

[JQUERY] jQuery로 자동 높이 애니메이션 요소

JQUERY

jQuery로 자동 높이 애니메이션 요소

해결법


  1. 1.그리고 함께 :

    그리고 함께 :

    var el = $('#first'),
        curHeight = el.height(),
        autoHeight = el.css('height', 'auto').height();
    el.height(curHeight).animate({height: autoHeight}, 1000);
    

  2. 2.IMO이 깨끗한 쉬운 솔루션입니다 :

    IMO이 깨끗한 쉬운 솔루션입니다 :

    $("#first").animate({height: $("#first").get(0).scrollHeight}, 1000 );
    

    설명 : DOM 이미 확장 된 DIV 자동 높이에 때 세트가 무슨 크기 초기 렌더링에서 알고있다. 이 속성은 scrollHeight로 DOM 노드에 저장된다. 우리는 단지 GET (0)를 호출하여 jQuery를 요소에서 DOM 요소를 가져가 다음 우리는 속성에 액세스 할 수 있습니다.

    애니메이션이 완료되면 콜백 함수를 추가하면 더 큰 응답을 허용 자동차에 높이를 설정합니다 (신용 크리스 윌리엄스) :

    $('#first').animate({
        height: $('#first').get(0).scrollHeight
    }, 1000, function(){
        $(this).height('auto');
    });
    

  3. 3.이것은 기본적으로 Box9으로 대답과 같은 방법입니다하지만 난 당신이 더 애니메이션 매개 변수가와 같은 코드를 반복 피곤해야하는 경우를 위해, 일반 애니메이션과 같은 인수를 취하는 좋은 JQuery와 플러그인에 싸서 :

    이것은 기본적으로 Box9으로 대답과 같은 방법입니다하지만 난 당신이 더 애니메이션 매개 변수가와 같은 코드를 반복 피곤해야하는 경우를 위해, 일반 애니메이션과 같은 인수를 취하는 좋은 JQuery와 플러그인에 싸서 :

    ;(function($)
    {
      $.fn.animateToAutoHeight = function(){
      var curHeight = this.css('height'),
          height = this.css('height','auto').height(),
          duration = 200,
          easing = 'swing',
          callback = $.noop,
          parameters = { height: height };
      this.css('height', curHeight);
      for (var i in arguments) {
        switch (typeof arguments[i]) {
          case 'object':
            parameters = arguments[i];
            parameters.height = height;
            break;
          case 'string':
            if (arguments[i] == 'slow' || arguments[i] == 'fast') duration = arguments[i];
            else easing = arguments[i];
            break;
          case 'number': duration = arguments[i]; break;
          case 'function': callback = arguments[i]; break;
        }
      }
      this.animate(parameters, duration, easing, function() {
        $(this).css('height', 'auto');
        callback.call(this, arguments);
      });
      return this;
      }
    })(jQuery);
    

    편집 : 이제 체인 방식 및 클리너


  4. 4.더 나은 솔루션은 요소의 높이를 설정하는 JS에 의존하지 않을 것입니다. 다음은 전체 ( "자동") 높이 고정 된 높이 요소를 애니메이션 솔루션입니다 :

    더 나은 솔루션은 요소의 높이를 설정하는 JS에 의존하지 않을 것입니다. 다음은 전체 ( "자동") 높이 고정 된 높이 요소를 애니메이션 솔루션입니다 :

    var $selector = $('div');
        $selector
            .data('oHeight',$selector.height())
            .css('height','auto')
            .data('nHeight',$selector.height())
            .height($selector.data('oHeight'))
            .animate({height: $selector.data('nHeight')},400);
    

    https://gist.github.com/2023150


  5. 5.이 작동하고 그것은 이전 솔루션에 비해 간단하다 :

    이 작동하고 그것은 이전 솔루션에 비해 간단하다 :

    CSS :

    #container{
      height:143px;  
    }
    
    .max{
      height: auto;
      min-height: 143px;
    }
    

    JS :

    $(document).ready(function() {
        $("#container").click(function() {      
            if($(this).hasClass("max")) {
                $(this).removeClass("max");
            } else {
                $(this).addClass("max");
            }
    
        })
    });
    

    참고 :이 솔루션은 jQuery를 UI를 필요로


  6. 6.

    var h = document.getElementById('First').scrollHeight;
    $('#First').animate({ height : h+'px' },300);
    

  7. 7.당신은 항상 변수로 래퍼의 #first 및 저장 높이 높이의 자식 요소를 래핑 할 수 있습니다. 이 예쁜 또는 가장 효율적인 응답하지 않을 수도 있습니다,하지만 트릭을 수행합니다.

    당신은 항상 변수로 래퍼의 #first 및 저장 높이 높이의 자식 요소를 래핑 할 수 있습니다. 이 예쁜 또는 가장 효율적인 응답하지 않을 수도 있습니다,하지만 트릭을 수행합니다.

    여기에 내가 리셋을 포함 바이올린입니다.

    그러나 당신의 목적을 위해, 여기에 고기 및 감자입니다 :

    $(function(){
    //wrap everything inside #first
    $('#first').children().wrapAll('<div class="wrapper"></div>');
    //get the height of the wrapper 
    var expandedHeight = $('.wrapper').height();
    //get the height of first (set to 200px however you choose)
    var collapsedHeight = $('#first').height();
    //when you click the element of your choice (a button in my case) #first will animate to height auto
    $('button').click(function(){
        $("#first").animate({
            height: expandedHeight            
        })
    });
    });​
    

  8. 8.사용 slideDown 및 slideUp

    사용 slideDown 및 slideUp

    $("div:first").click(function(){ $("#first").slideDown(1000); });
    

  9. 9.나는 그것을 해결하기 위해 관리 : D 코드를을 heres.

    나는 그것을 해결하기 위해 관리 : D 코드를을 heres.

    var divh = document.getElementById('first').offsetHeight;
    $("#first").css('height', '100px');
    $("div:first").click(function() {
      $("#first").animate({
        height: divh
      }, 1000);
    });
    

  10. 10.당신은 자동으로 높이 등을 설정하는 콜백을 추가하여 창 크기 변화에 Liquinaut의 대답은 반응 할 수 있습니다.

    당신은 자동으로 높이 등을 설정하는 콜백을 추가하여 창 크기 변화에 Liquinaut의 대답은 반응 할 수 있습니다.

    $("#first").animate({height: $("#first").get(0).scrollHeight}, 1000, function() {$("#first").css({height: "auto"});});
    

  11. 11.요소가 렌더링 된 후 기본적으로 높이 자동으로 당신을 위해에만 사용할 수 있습니다. 당신은 고정 높이를 설정하거나 요소가 표시되지 않는 경우는 어떠한 트릭도없이 액세스 할 수없는 경우.

    요소가 렌더링 된 후 기본적으로 높이 자동으로 당신을 위해에만 사용할 수 있습니다. 당신은 고정 높이를 설정하거나 요소가 표시되지 않는 경우는 어떠한 트릭도없이 액세스 할 수없는 경우.

    다행히 당신이 사용할 수있는 몇 가지 트릭이있다.

    복제 요소는 외부보기를 표시 그것을 높이 자동 줄 당신은 클론을 받아 주요 요소에 대해 나중에 사용할 수 있습니다. 나는이 기능을 사용하고 잘 작동하는 것 같다.

    jQuery.fn.animateAuto = function(prop, speed, callback){
        var elem, height, width;
    
        return this.each(function(i, el){
            el = jQuery(el), elem =    el.clone().css({"height":"auto","width":"auto"}).appendTo("body");
            height = elem.css("height"),
            width = elem.css("width"),
            elem.remove();
    
            if(prop === "height")
                el.animate({"height":height}, speed, callback);
            else if(prop === "width")
                el.animate({"width":width}, speed, callback);  
            else if(prop === "both")
                el.animate({"width":width,"height":height}, speed, callback);
        });   
    }
    

    용법:

    $(".animateHeight").bind("click", function(e){
        $(".test").animateAuto("height", 1000); 
    });
    
    $(".animateWidth").bind("click", function(e){
        $(".test").animateAuto("width", 1000);  
    });
    
    $(".animateBoth").bind("click", function(e){
        $(".test").animateAuto("both", 1000); 
    });
    

  12. 12.당신은 항상이 작업을 수행 할 수 있습니다

    당신은 항상이 작업을 수행 할 수 있습니다

    jQuery.fn.animateAuto = function(prop, speed, callback){
    var elem, height, width;
    return this.each(function(i, el){
        el = jQuery(el), elem = el.clone().css({"height":"auto","width":"auto"}).appendTo("body");
        height = elem.css("height"),
        width = elem.css("width"),
        elem.remove();
    
        if(prop === "height")
            el.animate({"height":height}, speed, callback);
        else if(prop === "width")
            el.animate({"width":width}, speed, callback);  
        else if(prop === "both")
            el.animate({"width":width,"height":height}, speed, callback);
    });  
    }
    

    여기에 바이올린입니다 : http://jsfiddle.net/Zuriel/faE9w/2/


  13. 13.귀하의 선택기는 일치하지 않는 것. 당신의 요소는 '최초'의 ID를 가지고, 또는 모든 사업부의 첫 번째 요소입니다합니까?

    귀하의 선택기는 일치하지 않는 것. 당신의 요소는 '최초'의 ID를 가지고, 또는 모든 사업부의 첫 번째 요소입니다합니까?

    더 안전한 솔루션 '이'를 사용하는 것입니다 :

    // assuming the div you want to animate has an ID of first
    $('#first').click(function() {
      $(this).animate({ height : 'auto' }, 1000);
    });
    

  14. 14.이걸로 해봐 ,

    이걸로 해봐 ,

    var height;
    $(document).ready(function(){
        $('#first').css('height','auto');
        height = $('#first').height();
        $('#first').css('height','200px');
    })
    
     $("div:first").click(function(){
      $("#first").animate({
        height: height
      }, 1000 );
    });
    

  15. 15.안녕들. 여기에 내가 같은 일을 쓴 플러그인 JQuery와는뿐만 아니라 당신이 국경 상자 상자 크기 조정 세트가있을 때 발생합니다 높이의 차이를 차지하고있다.

    안녕들. 여기에 내가 같은 일을 쓴 플러그인 JQuery와는뿐만 아니라 당신이 국경 상자 상자 크기 조정 세트가있을 때 발생합니다 높이의 차이를 차지하고있다.

    또한, Y 축에 따라서 그 수축에 의해 그 요소를 숨겨 플러그인은 "yShrinkOut"를 포함.

    // -------------------------------------------------------------------
    // Function to show an object by allowing it to grow to the given height value.
    // -------------------------------------------------------------------
    $.fn.yGrowIn = function (growTo, duration, whenComplete) {
    
        var f = whenComplete || function () { }, // default function is empty
            obj = this,
            h = growTo || 'calc', // default is to calculate height
            bbox = (obj.css('box-sizing') == 'border-box'), // check box-sizing
            d = duration || 200; // default duration is 200 ms
    
        obj.css('height', '0px').removeClass('hidden invisible');
        var padTop = 0 + parseInt(getComputedStyle(obj[0], null).paddingTop), // get the starting padding-top
            padBottom = 0 + parseInt(getComputedStyle(obj[0], null).paddingBottom), // get the starting padding-bottom
            padLeft = 0 + parseInt(getComputedStyle(obj[0], null).paddingLeft), // get the starting padding-left
            padRight = 0 + parseInt(getComputedStyle(obj[0], null).paddingRight); // get the starting padding-right
        obj.css('padding-top', '0px').css('padding-bottom', '0px'); // Set the padding to 0;
    
        // If no height was given, then calculate what the height should be.
        if(h=='calc'){ 
            var p = obj.css('position'); // get the starting object "position" style. 
            obj.css('opacity', '0'); // Set the opacity to 0 so the next actions aren't seen.
            var cssW = obj.css('width') || 'auto'; // get the CSS width if it exists.
            var w = parseInt(getComputedStyle(obj[0], null).width || 0) // calculate the computed inner-width with regard to box-sizing.
                + (!bbox ? parseInt((getComputedStyle(obj[0], null).borderRightWidth || 0)) : 0) // remove these values if using border-box.
                + (!bbox ? parseInt((getComputedStyle(obj[0], null).borderLeftWidth || 0)) : 0) // remove these values if using border-box.
                + (!bbox ? (padLeft + padRight) : 0); // remove these values if using border-box.
            obj.css('position', 'fixed'); // remove the object from the flow of the document.
            obj.css('width', w); // make sure the width remains the same. This prevents content from throwing off the height.
            obj.css('height', 'auto'); // set the height to auto for calculation.
            h = parseInt(0); // calculate the auto-height
            h += obj[0].clientHeight // calculate the computed height with regard to box-sizing.
                + (bbox ? parseInt((getComputedStyle(obj[0], null).borderTopWidth || 0)) : 0) // add these values if using border-box.
                + (bbox ? parseInt((getComputedStyle(obj[0], null).borderBottomWidth || 0)) : 0) // add these values if using border-box.
                + (bbox ? (padTop + padBottom) : 0); // add these values if using border-box.
            obj.css('height', '0px').css('position', p).css('opacity','1'); // reset the height, position, and opacity.
        };
    
        // animate the box. 
        //  Note: the actual duration of the animation will change depending on the box-sizing.
        //      e.g., the duration will be shorter when using padding and borders in box-sizing because
        //      the animation thread is growing (or shrinking) all three components simultaneously.
        //      This can be avoided by retrieving the calculated "duration per pixel" based on the box-sizing type,
        //      but it really isn't worth the effort.
        obj.animate({ 'height': h, 'padding-top': padTop, 'padding-bottom': padBottom }, d, 'linear', (f)());
    };
    
    // -------------------------------------------------------------------
    // Function to hide an object by shrinking its height to zero.
    // -------------------------------------------------------------------
    $.fn.yShrinkOut = function (d,whenComplete) {
        var f = whenComplete || function () { },
            obj = this,
            padTop = 0 + parseInt(getComputedStyle(obj[0], null).paddingTop),
            padBottom = 0 + parseInt(getComputedStyle(obj[0], null).paddingBottom),
            begHeight = 0 + parseInt(obj.css('height'));
    
        obj.animate({ 'height': '0px', 'padding-top': 0, 'padding-bottom': 0 }, d, 'linear', function () {
                obj.addClass('hidden')
                    .css('height', 0)
                    .css('padding-top', padTop)
                    .css('padding-bottom', padBottom);
                (f)();
            });
    };
    

    내가 사용하는 매개 변수의 생략 또는 기본값을 적용하기 위해 null로 설정할 수 있습니다. 내가 사용하는 매개 변수 :


  16. 16.슬라이드 토글 (Box9의 대답은 확대)

    슬라이드 토글 (Box9의 대답은 확대)

    $ ( "#은 클릭 나"). ((기능을 클릭) { VAR 엘 = $ ( '# 먼저'); curHeight el.height = (); autoHeight를 el.css = ( '높이', '자기')의 높이 ().; finHeight = $ ( '# 첫 번째'). 데이터 1 == ( '클릭')? "20 픽셀"; autoHeight를; $ ( '# 먼저') 데이터 ($ (이) .DATA이 (==) 거짓 일 '클릭' '클릭': true)를.; el.height (curHeight) .animate ({신장 finHeight}); }); #first {폭 : 100 % 신장 20 픽셀, 오버플 : 숨겨진} <스크립트 SRC = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> <사업부 ID는 = "클릭 나"> 로렘 입숨 당근, 향상된 학부 개발자 그러나 나는 고통을 기쁨을 비난과 칭찬의 잘못된 생각은, 시스템의 전체 계정을 태어난 방법 모두 당신에게 설명하고, 진리의 위대한 탐험가의 실제 가르침을 상세히 설명하고 인간의 행복의 마스터 빌더에서 전개됩니다해야합니다. 기쁨의 없음은 통증이나 피합니다이기 때문에,


  17. 17.나는이 스레드가 오래된 경우에도이 답변을 게시하고있다. 나는 나에 대한 작업에 허용 답변을 얻을 수 없었다. 이 사람은 잘 작동하고 매우 간단하다.

    나는이 스레드가 오래된 경우에도이 답변을 게시하고있다. 나는 나에 대한 작업에 허용 답변을 얻을 수 없었다. 이 사람은 잘 작동하고 매우 간단하다.

    나는이 데이터로 할 각 사업부의 높이를로드

    $('div').each(function(){
        $(this).data('height',$(this).css('height'));
        $(this).css('height','20px');
    });
    

    그럼 난 그냥 클릭에 애니메이션 때 사용합니다.

    $('div').click(function(){
        $(this).css('height',$(this).data('height'));
    });
    

    나는 JQuery와 애니메이션을 사용하지 않도록 나는, CSS 전환을 사용하고,하지만 당신은 그냥 같은 애니메이션을 할 수 있습니다.


  18. 18.당신은 데이터 속성에 저장할 수 있습니다.

    당신은 데이터 속성에 저장할 수 있습니다.

    $('.colapsable').each(function(){
        $(this).attr('data-oheight',$(this).height());
        $(this).height(100);
    });
    
    $('.colapsable h2:first-child').click(function(){
        $(this).parent('.colapsable').animate({
                height: $(this).parent('.colapsible').data('oheight')
            },500);
        }
    });
    

  19. 19.나는 여러에 대해이 기능은 저도 같은 문제로 실행 단축 코드 워드 프레스에이 구현 한 페이지에 많은 지역의 읽을 필요했습니다.

    나는 여러에 대해이 기능은 저도 같은 문제로 실행 단축 코드 워드 프레스에이 구현 한 페이지에 많은 지역의 읽을 필요했습니다.

    기술적으로 모든의 디자인 페이지 범위의 더는 고정 된 높이를 읽어 보시기 바랍니다. 그리고 토글와 자동 높이에 개별적으로 확장 할 수 있기를 원했다. 첫 번째 클릭 : 두 번째 클릭 '텍스트 범위의 전체 높이로 확장': '70 픽셀의 기본 높이 붕괴 다시'

    html로

     <span class="read-more" data-base="70" data-height="null">
         /* Lots of text determining the height of this span */
     </span>
     <button data-target='read-more'>Read more</button>
    

    CSS

    span.read-more {
        position:relative;
        display:block;
        overflow:hidden;
    }
    

    그래서이 외모 매우 간단 위의 데이터베이스 속성은 내가 필요한 고정 높이를 설정해야합니다. 데이터 높이 특성 I는 요소의 실제 (동적) 높이를 저장하는데 사용.

    JQuery와 부품

    jQuery(document).ready(function($){
    
      $.fn.clickToggle = function(func1, func2) {
          var funcs = [func1, func2];
          this.data('toggleclicked', 0);
          this.click(function() {
              var data = $(this).data();
              var tc = data.toggleclicked;
              $.proxy(funcs[tc], this)();
              data.toggleclicked = (tc + 1) % 2;
          });
          return this;
      };
    
        function setAttr_height(key) {
            $(key).each(function(){
                var setNormalHeight = $(this).height();
                $(this).attr('data-height', setNormalHeight);
                $(this).css('height', $(this).attr('data-base') + 'px' );
            });
        }
        setAttr_height('.read-more');
    
        $('[data-target]').clickToggle(function(){
            $(this).prev().animate({height: $(this).prev().attr('data-height')}, 200);
        }, function(){
            $(this).prev().animate({height: $(this).prev().attr('data-base')}, 200);
        });
    
    });
    

    우선 내 제 1 및 제 2 클릭에 대한 clickToggle 기능을 사용했습니다. 두 번째 함수는 더 중요하다 setAttr_height ()는 .read-이상의 구성 요소 모두가베이스 높이 속성 페이지로드에 설정된 실제 높이를 갖는다. 베이스 높이 JQuery와 CSS 기능을 통해 설정된다 그 후.

    우리의 속성을 모두 설정으로 우리는 이제 부드러운 방식으로 전환 할 수 있습니다. 만 장 원하는 (고정) 높이로 데이터베이스와 자신의 ID에 대한 .read - 더 클래스 전환

    당신은 모두가 바이올린 뿐인에서 작업을 볼 수 있습니다


  20. 20.당신이 원하는 모든이 보여주는 것입니다 및 숨기기 사업부를 말한다면,이 코드는 jQuery를의 애니메이션을 사용하게됩니다. 당신은 당신이 원하는 높이의 대부분의 jQuery 애니메이션을하거나 0 픽셀에 애니메이션으로 애니메이션을 속일 수 있습니다. jQuery를 바로 자동으로 변환하기 위해 jQuery를하여 높이 설정이 필요합니다. 변환 다음 .animate는 요소가 .CSS (자동 높이)에 스타일을 = ""추가 그래서.

    당신이 원하는 모든이 보여주는 것입니다 및 숨기기 사업부를 말한다면,이 코드는 jQuery를의 애니메이션을 사용하게됩니다. 당신은 당신이 원하는 높이의 대부분의 jQuery 애니메이션을하거나 0 픽셀에 애니메이션으로 애니메이션을 속일 수 있습니다. jQuery를 바로 자동으로 변환하기 위해 jQuery를하여 높이 설정이 필요합니다. 변환 다음 .animate는 요소가 .CSS (자동 높이)에 스타일을 = ""추가 그래서.

    나는이 작품을 본 가장 깨끗한 방법은 당신이 기대하는 높이의 주위에, 그것은 자동을 설정하자 매우 원활한 완료 권리를 볼 수에 애니메이션이다. 당신은 당신도 애니메이션의 과거를 기대할 수 있으며 다시 스냅됩니다. 0의 기간에서 0 픽셀하는 애니메이션 그냥 단순히 자동 높이 요소 높이 삭제합니다. 인간의 눈에, 그것은 어쨌든 애니메이션 보인다. 즐겨..

        jQuery("div").animate({
             height: "0px"/*or height of your choice*/
        }, {
             duration: 0,/*or speed of your choice*/
             queue: false, 
             specialEasing: {
                 height: "easeInCirc"
            },
             complete: function() {
                 jQuery(this).css({height:"auto"});
            }
        });
    

    죄송합니다 나는 이것이 이전 게시물입니다 알지만, 나는 이것이이 게시물에 건너와 jQuery 아직이 기능을 원하는 사용자에게 관련 될 것이다 느꼈다.


  21. 21.내가 찾고 멋지다 정확히 무엇을하지 뭔가를 함께 넣어. 요소의 scrollHeight를 사용하면 당신에게 그것이 DOM에로드 할 때의 높이를 가져옵니다.

    내가 찾고 멋지다 정확히 무엇을하지 뭔가를 함께 넣어. 요소의 scrollHeight를 사용하면 당신에게 그것이 DOM에로드 할 때의 높이를 가져옵니다.

    VAR의도 Clicker document.querySelectorAll = ( '식자.'); clickers.forEach (리모콘 => { clicker.addEventListener ({), 기능 (예 '를 클릭' VAR 노드 e.target.parentNode.childNodes = [5]; 경우 (node.style.height == "0 픽셀"|| node.style.height == "") { $ (노드) .animate ({신장 node.scrollHeight}); } 다른 { $ (노드) .animate ({높이 : 0}); } }); }); .대답{ 폰트 크기 : 15 픽셀; 파란색; 높이 : 0 픽셀; 오버 플로우 : 숨겨진; }

    이 애니메이션은 시험기 <스팬 클래스 = "리모콘"> 나를 클릭

    나는 웹 사이트에 자주 묻는 질문을 표시하고 당신이 싶은 그림이를 사용하는 것입니다. 자바 스크립트는이 내 면도기 코드에 의해 만들어진 자주 묻는 질문 div의 모든 작업을 할 수 있습니다. Scrollheight는 DOM 부하에 응답 엘리먼트의 높이이다. 행복 : 코딩 로렘 입숨 슬픔 앉아 AMET, 내 잘못 quis vidit autem. 아니 내 잘못 보라 inani efficiantur, 몰리스 admodum accusata ID는, EAM dolore nemore 유럽 연합 (EU)이 없습니다. Mutat partiendo 개 우스, PRI의 음주 운전 vulputate 유럽 연합 (EU). 마주 mazim noluisse oportere의 ID입니다. 정액 porro labore에서, 추정 accumsan euripidis scripserit 에이. Albucius scaevola elaboraret 우스 유럽 연합 (EU). 광고 나오지 vivendo persecuti, harum movet instructior EAM 에이. <스크립트 SRC = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">

  22. from https://stackoverflow.com/questions/5003220/animate-element-to-auto-height-with-jquery by cc-by-sa and MIT license