web-dev-qa-db-ja.com

jQueryを使用して要素を自動高さにアニメーション化する

<div>200pxからautoの高さにアニメーション化したい。私はそれを動作させることができないようです。誰もが方法を知っていますか?

コードは次のとおりです。

$("div:first").click(function(){
  $("#first").animate({
    height: "auto"
  }, 1000 );
});
164
Daniel
  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);
246
David Tang

IMOこれは最もクリーンで簡単なソリューションです。

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

説明:DOMは、最初のレンダリングから、自動高さに設定されたときに展開されたdivのサイズを既に知っています。このプロパティは、scrollHeightとしてDOMノードに保存されます。 get(0)を呼び出してjQuery要素からDOM要素を取得するだけで、プロパティにアクセスできます。

コールバック関数を追加して高さを自動に設定すると、アニメーションが完了した後の応答性が向上します(クレジット chris-williams ):

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

これは基本的にBox9による答えと同じアプローチですが、ニースでラップしましたjquery plugin that 通常のアニメーションと同じ引数を取りますより多くのアニメーション化されたパラメータと同じコードを繰り返し繰り返すことにうんざりします。

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

編集:チェーン可能かつクリーンになりました

24
w0ps

より良いソリューションは、要素の高さを設定するために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/202315

23
Tim Hettler

これは機能しており、以前のソリューションよりも簡単です:

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が必要です

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

常に#firstの子要素をラップし、ラッパーの高さを変数として保存できます。これは最もきれいな、または最も効率的な答えではないかもしれませんが、トリックを行います。

ここに fiddle があり、ここにリセットが含まれています。

しかし、あなたの目的のために、ここに肉とジャガイモがあります:

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

私はそれを修正することができました:D heres the code。

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

slideDown および slideUp を使用します

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

基本的に、高さの自動は要素がレンダリングされた後にのみ利用可能です。固定の高さを設定した場合、または要素が表示されていない場合、トリックなしでアクセスすることはできません。

幸いなことに、使用できるいくつかのトリックがあります。

要素のクローンを作成し、ビューの外に表示して高さを自動にします。クローンから取り出して、後でメイン要素に使用できます。私はこの機能を使用し、うまく機能しているようです。

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); 
});
4
Stan George

高さを自動に戻すコールバックを追加することで、ウィンドウサイズの変更に対応するLiquinautの回答を作成できます。

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

あなたはいつでもこれを行うことができます:

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/

3
Zuriel

これを試して、

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

BORDER-BOXで動作するものは次のとおりです...

こんにちは、みんな。同じことをするために書いたjQueryプラグインを次に示しますが、box-sizingborder-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の高さを設定する場合は、このパラメーターを使用します。
  • duration:アニメーションの継続時間(明らかに)。
  • whenComplete:アニメーションが完了したときに実行する関数。
2
Lopsided

スライドの切り替え( 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>
2
che-azeh

セレクターが一致していないようです。要素のIDは「first」ですか、それともすべてのdivの最初の要素ですか?

より安全な解決策は、「this」を使用することです。

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

同じ機能に遭遇したWordpressショートコードにこれを実装する1ページに複数の読み取り領域があるため、この機能が必要でした。

技術的には、ページ上のすべての続きのスパンの高さを固定して設計します。そして、トグルを使用して、それらを個別に自動高さまで拡張できるようにしたかったのです。最初のクリック:「テキストスパンの最大の高さに展開する」、2番目のクリック:「デフォルトの高さである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;
}

したがって、上記の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);
    });

});

最初に、1回目と2回目のクリックにclickToggle関数を使用しました。 2番目の関数はより重要です。setAttr_height()すべての.read-more要素には、ページの読み込み時にbase-height属性の実際の高さが設定されています。その後、jquery css関数を介してベースの高さが設定されます。

両方の属性を設定したら、スムーズに切り替えることができます。 data-baseを目的の(固定)高さに変更し、独自のIDの.read-moreクラスを切り替えるだけです

あなたはすべてそれがフィドルで動作しているのを見ることができます FIDDLE

JQuery UIは必要ありません

1
Paul

データ属性に保存できます。

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

このスレッドは古いですが、この回答を投稿しています。受け入れられる答えを得ることができませんでした。これはうまく機能し、非常に簡単です。

必要な各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アニメーションを使用しませんが、同じようにアニメーション化できます。

1
Leeish

私が探していたものを正確に実行し、見栄えの良いものをまとめました。要素のscrollHeightを使用すると、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>
0
JimmyTwoShoes