有没有一种方法可以使用CSS对display:none进行动画显示:block,以便隐藏的div向下滑动而不是突然出现,或者我应该以不同的方式解决这个问题?
$(document).ready(function() {
$('#box').click(function() {
$(this).find(".hidden").toggleClass('open');
});
});
#box {
height:auto;
background:#000;
color:#fff;
cursor:pointer;
}
.hidden {
height:200px;
display:none;
}
.hidden.open {
display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box">
Initial Content
<div class="hidden">
This is hidden content
</div>
</div>
是的,有一个办法: http://jsfiddle.net/6C42Q/12/
通过使用CSS3过渡,并操纵高度,而不是显示属性:
.hidden {
height: 0px;
-webkit-transition: height 0.5s linear;
-moz-transition: height 0.5s linear;
-ms-transition: height 0.5s linear;
-o-transition: height 0.5s linear;
transition: height 0.5s linear;
}
.hidden.open {
height: 200px;
-webkit-transition: height 0.5s linear;
-moz-transition: height 0.5s linear;
-ms-transition: height 0.5s linear;
-o-transition: height 0.5s linear;
transition: height 0.5s linear;
}
更多此处:单击纯 CSS 时向下滑动 div?
既然您已经在使用 jQuery,最简单的事情就是使用 slipDown()。 http://api.jquery.com/slidedown/
还有slideToggle()。
那么您不需要手动执行所有特定于浏览器的转换 CSS。
我喜欢 CSS 过渡的想法,但它仍然很不稳定。有时,最大高度必须设置为非常高的数字,因为动态内容会导致过渡毫无用处,因为它非常跳跃。所以,我又回到了 jQuery,但它也有自己的缺点。内联元素是跳跃的。
我发现这对我有用:
$(this).find('.p').stop().css('display','block').hide().slideDown();
停止会停止所有之前的转换。 css 确保它被视为块元素,即使它不是。 hide 隐藏该元素,但 jquery 会将其记住为块元素。 最后,slideDown 通过向下滑动来显示元素。
我们可以使用
visibility: hidden
到 visibility: visible
来代替 display: none
到 display: block
属性。使用 max-height
而不是 hight
应保持元素具有自动高度。
看这个例子:
function toggleSlide () {
const div = document.querySelector('div')
if (div.classList.contains('open')) {
div.classList.remove('open')
} else {
div.classList.add('open')
}
}
div {
visibility: hidden;
transition: visibility .5s, max-height .5s;
max-height: 0;
overflow: hidden;
/* additional style */
background: grey;
color: white;
padding: 0px 12px;
margin-bottom: 8px;
}
div.open {
visibility: visible;
/* Set max-height to something bigger than the box could ever be */
max-height: 100px;
}
<div>
<p>First paragraph</p>
<p>Second paragraph</p>
</div>
<button
onclick="toggleSlide()"
>
toggle slide
</button>
怎么样
$("#yourdiv").animate({height: 'toggle'})
;
切换将打开/关闭您的 div,并且动画应使其从下方显示。在这种情况下,您不需要特定的 CSS 来“隐藏”它。
我在我的 React 站点中为导航标题做了这个解决方法。
这是常规的可见 CSS 类
.article-header {
position: fixed;
top: 0;
transition: top 0.2s ease-in-out;
}
这是附加到 div 的类(在我的情况下滚动时)
.hidden {
top: -50px !important;
transition: top 0.5s ease-in-out;
}
您也可以使用
$('#youDiv').slideDown('fast');
或者你可以知道活动的 div 上升,然后被调用的 div 下降
$('.yourclick').click(function(e) {
var gett = $(this).(ID);
$('.youractiveDiv').slideUp('fast', function(){
$('.'+gett).slideDown(300);
});
});
类似这样的事情。