programing

jQuery를 사용하여 요소를 자동 높이로 애니메이션화

yoursource 2023. 7. 26. 22:50
반응형

jQuery를 사용하여 요소를 자동 높이로 애니메이션화

나는 애니메이션을 원합니다.<div>200pxauto. 요.하지만 잘 될 것 같지는 않아요.방법 아는 사람?

코드는 다음과 같습니다.

$("div:first").click(function(){
  $("#first").animate({
    height: "auto"
  }, 1000 );
});
  1. 현재 높이 저장:

    var curHeight = $('#first').height();
    
  2. 높이를 일시적으로 자동으로 전환:

    $('#first').css('height', 'auto');
    
  3. 자동 높이 가져오기:

    var autoHeight = $('#first').height();
    
  4. 으로 다시 합니다.curHeight에 애니메이션을 제공합니다.autoHeight:

    $('#first').height(curHeight).animate({height: autoHeight}, 1000);
    

그리고 함께:

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

IMO 이것은 가장 깨끗하고 쉬운 솔루션입니다.

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

: 되었을 때 있습니다.DOM은 자동 높이로 설정될 때 확장된 div의 크기를 초기 렌더링을 통해 이미 알고 있습니다.에 "DOM 파일"로 됩니다.scrollHeight는 jQueryElement를 DOMElement로 .get(0)그러면 우리는 그 재산에 접근할 수 있습니다.

높이를 자동으로 설정하는 콜백 기능을 추가하면 애니메이션이 완료된 후 응답성이 향상됩니다(크레딧 크리스 윌리엄스).

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

이것은 기본적으로 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);

편집: 체인이 가능하고 깨끗합니다.

더 나은 솔루션은 요소의 높이를 설정하는 데 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

이것은 효과적이며 이전의 솔루션보다 간단합니다.

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가 필요합니다.

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

항상 #의 자식 요소를 먼저 래핑하고 래퍼의 높이를 변수로 저장할 수 있습니다.이것이 가장 예쁘거나 가장 효율적인 대답은 아닐 수도 있지만, 효과적입니다.

여기 재설정을 포함한 바이올린이 있습니다.

하지만 당신의 목적을 위해, 여기에 고기와 감자가 있습니다.

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

slideDownslideUp 사용

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

저는 가까스로 그것을 고쳤습니다: 코드를 삭제합니다.

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

높이를 다시 auto로 설정하는 콜백을 추가하여 창 크기 변경에 대응하는 Liquinaut의 응답을 만들 수 있습니다.

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

기본적으로 높이 자동은 요소가 렌더링된 후에만 사용할 수 있습니다.고정 높이를 설정하거나 요소가 표시되지 않으면 트릭 없이 액세스할 수 없습니다.

다행히도 당신이 사용할 수 있는 몇 가지 속임수가 있습니다.

요소를 복제하여 뷰 외부에 표시하고 높이를 자동으로 지정하면 해당 요소를 복제본에서 가져와 나중에 기본 요소에 사용할 수 있습니다.저는 이 기능을 사용하는데 잘 작동하는 것 같습니다.

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

선택한 항목이 일치하지 않습니다.당신의 요소는 ID가 'first'인가요, 아니면 모든 div의 첫 번째 요소인가요?

더 안전한 해결책은 '이것'을 사용하는 것입니다.

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

다음 작업을 언제든지 수행할 수 있습니다.

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/

이거 드셔보세요.

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

BORDER-BOX와 함께 작동하는...

안녕 친구들.제가 위해 플러그인이 , 이 은 여기제작플 jQuery 이 있을 때 합니다. 동일한 작업을 수행하기 위해 작성했지만, 사용자가 사용할 때 발생할 높이 차이도 설명합니다.box-sizing로 설정한.border-box.

요소를 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로 설정할 수 있습니다.사용한 매개 변수:

  • growTo: 모든 계산을 재정의하고 개체가 커질 CSS 높이를 설정하려면 이 매개 변수를 사용합니다.
  • 기간:애니메이션의 지속 시간입니다.
  • 완료된 경우:애니메이션이 완료되면 실행할 기능입니다.

저는 이 기능이 한 페이지에 있는 여러 읽기 영역에서 워드프레스 단축 코드로 구현하기 위해 필요했습니다. 같은 문제가 발생했습니다.

기술적으로 페이지의 모든 읽기 범위는 높이가 고정되어 있습니다.저는 토글을 사용하여 자동 높이로 개별적으로 확장할 수 있기를 원했습니다.첫 번째 클릭: '텍스트 범위의 전체 높이로 확장', 두 번째 클릭: '기본 높이인 70px로 축소'

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

그래서 이 위는 매우 단순해 보입니다.data-base속성 필요한 고정 높이를 설정해야 합니다.data-height요소의 실제(동적) 높이를 저장하는 데 사용되는 속성입니다.

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

});

첫 번째와 두 번째 클릭에 클릭 토글 기능을 사용했습니다.합니다: 두번째기더중니다합요능이다▁the▁is니.setAttr_height() 두모.read-more됩니다.base-height.그 후 함수를 통해 합니다.그 후 jquery css 함수를 통해 기본 높이가 설정됩니다.

두 속성을 모두 설정하면 이제 두 속성을 원활하게 전환할 수 있습니다.만 합니다.data-base원하는 (고정된) 높이로 이동하고 자신의 ID에 대한 .read-more 클래스를 전환합니다.

당신은 모두 바이올린으로 작동하는 것을 볼 수 있습니다.

jQuery UI가 필요하지 않음

슬라이드 전환(Box9의 응답 확장)

$("#click-me").click(function() {
  var el = $('#first'),
  curHeight = el.height(),
  autoHeight = el.css('height', 'auto').height(),
  finHeight = $('#first').data('click') == 1 ? "20px" : autoHeight;
  $('#first').data('click', $(this).data('click') == 1 ? false : true);
  el.height(curHeight).animate({height: finHeight});
});
#first {width: 100%;height: 20px;overflow:hidden;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="first">
  <div id="click-me">Lorem ipsum dolor sit amet, consectetur adipiscing elit</div>
  Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit,
</div>

만약 당신이 원하는 것이 단지 div를 보여주고 숨기는 것이라면, 이 코드는 당신이 jQuery를 애니메이션으로 사용할 수 있게 해줄 것입니다.jQuery가 원하는 높이의 대부분을 애니메이션으로 만들거나 애니메이션을 0px로 만들어 애니메이션을 속일 수 있습니다. jQuery는 자동으로 변환하기 위해 jQuery가 설정한 높이만 있으면 됩니다.따라서 .animate는 .vmx(높이:auto)가 변환하는 요소에 style="를 추가합니다.

제가 본 이 작업 중 가장 깨끗한 방법은 예상되는 높이까지 애니메이션을 만든 다음 자동으로 설정하고 올바르게 수행하면 매우 매끄럽게 보일 수 있습니다.여러분은 심지어 여러분이 기대하는 것을 애니메이션으로 만들 수도 있고, 그러면 그것은 빠르게 되돌아 올 것입니다.0의 지속 시간 동안 0px로 애니메이션을 만들면 요소 높이가 자동 높이로 떨어지게 됩니다.인간의 눈에는, 어쨌든 그것은 활기차게 보입니다.즐기세요..

    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에서 이 기능을 여전히 사용하는 사용자와 관련이 있을 것이라고 생각했습니다.

이 스레드가 오래되었음에도 불구하고 이 답변을 게시합니다.저는 저를 위해 일할 수 있는 승인된 답변을 얻지 못했습니다.이것은 잘 작동하고 꽤 간단합니다.

내가 원하는 각 div의 높이를 데이터에 로드합니다.

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

그러면 저는 클릭해서 애니메이션을 할 때 그것을 사용합니다.

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

나는 CSS 전환을 사용하고 있어서 jQuery animate를 사용하지 않지만, 당신은 똑같이 animate를 할 수 있습니다.

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

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

저는 제가 찾던 것을 정확하게 해주고 멋져 보이는 것을 조립했습니다.요소의 스크롤 높이를 사용하면 DOM에 로드되었을 때의 높이를 얻을 수 있습니다.

 var clickers = document.querySelectorAll('.clicker');
    clickers.forEach(clicker => {
        clicker.addEventListener('click', function (e) {
            var node = e.target.parentNode.childNodes[5];
            if (node.style.height == "0px" || node.style.height == "") {
                $(node).animate({ height: node.scrollHeight });
            }
            else {
                $(node).animate({ height: 0 });
            }
        });
    });
.answer{
        font-size:15px;
        color:blue;
        height:0px;
        overflow:hidden;
       
    }
 <div class="row" style="padding-top:20px;">
                <div class="row" style="border-color:black;border-style:solid;border-radius:4px;border-width:4px;">
                    <h1>This is an animation tester?</h1>
                    <span class="clicker">click me</span>
                    <p class="answer">
                        I will be using this to display FAQ's on a website and figure you would like this.  The javascript will allow this to work on all of the FAQ divs made by my razor code.  the Scrollheight is the height of the answer element on the DOM load.  Happy Coding :)
                         Lorem ipsum dolor sit amet, mea an quis vidit autem. No mea vide inani efficiantur, mollis admodum accusata id has, eam dolore nemore eu. Mutat partiendo ea usu, pri duis vulputate eu. Vis mazim noluisse oportere id. Cum porro labore in, est accumsan euripidis scripserit ei. Albucius scaevola elaboraret usu eu. Ad sed vivendo persecuti, harum movet instructior eam ei.
                    </p>
                </div>
            </div>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

언급URL : https://stackoverflow.com/questions/5003220/animate-element-to-auto-height-with-jquery

반응형