+-
如何给div边框添加过渡[重复]
这个问题在这里已经有了答案:
如何使用CSS将高度:0;过渡到高度:自动;? (51个回答)
封闭 3个月前.

我有以下代码。

$(document).ready(function(){
  $("#add").click(function(){
    $("#content").append("<p>New text</p>");
  });
});
#content{
  -webkit-transition: all .5s ease;
  -moz-transition: all .5s ease;
  transition: all .5s ease;
  padding: 15px;
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
<p>TEXT</p>
</div>
<button id="add">Add text</button>

我希望当我点击按钮添加,内容div将有一个过渡,当他扩大.我已经尝试与以下动画css :

-webkit-transition: all .5s ease;
-moz-transition: all .5s ease;
transition: all .5s ease;

我想给div添加一个过渡。

我也试过用 .show('slow');

2
投票

你可以使用另一个元素来实现。

$(document).ready(function() {
  function initBorder() {
    $("#content-border").css({
      height: $("#content").outerHeight(),
      width: $("#content").outerWidth(),
    });
  }

  initBorder();

  $("#add").click(function() {
    $("#content").append("<p>New text</p>");
    initBorder();
  });
});
#content {
  -webkit-transition: all .5s ease;
  -moz-transition: all .5s ease;
  transition: all .5s ease;
  padding: 15px;
  position: relative;
}

#content-border {
  position: absolute;
  left: 0;
  top: 0;
  border: 1px solid black;
  -webkit-transition: all .5s ease;
  -moz-transition: all .5s ease;
  transition: all .5s ease;
  box-sizing: border-box;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
  <p>TEXT</p>
  <div id="content-border"></div>
</div>

<button id="add">Add text</button>

我们可以使用淡入淡出功能来实现更平滑的过渡。

$(document).ready(function() {
  function initBorder() {
    $("#content-border").css({
      height: $("#content").outerHeight(),
      width: $("#content").outerWidth(),
    });
  }

  initBorder();

  $("#add").click(function() {
    $("#content").append("<p>New text</p>");
    $("#content").find("p").last().fadeOut(0).fadeIn(500);
    initBorder();
  });
});
#content {
  -webkit-transition: all .5s ease;
  -moz-transition: all .5s ease;
  transition: all .5s ease;
  padding: 15px;
  position: relative;
}

#content-border {
  position: absolute;
  left: 0;
  top: 0;
  border: 1px solid black;
  -webkit-transition: all .5s ease;
  -moz-transition: all .5s ease;
  transition: all .5s ease;
  box-sizing: border-box;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
  <p>TEXT</p>
  <div id="content-border"></div>
</div>

<button id="add">Add text</button>