我正在尝试制作一个类似于该slideToggle()
方法但使用velocity.js 的滑动切换淡入淡出动画 - 希望它会更加流畅。
因为我无法滚动到自动- 我将高度放在变量中并使用它来动画高度。我遇到的问题是高度值存储一次,如果页面稍微调整大小,则数字不再正确。- 另外 - 因为该区域在页面加载时被隐藏,(在它获得初始高度之后)我无法再次检查高度(如果发生窗口大小调整)
最终我想把它放到一个函数中,所以保持相对它的关键。
此外,如果您没有使用velocity.js,它基本上就像.animate() - 所以它不是问题的一部分。
HTML
<section>
<div class="button-w">
<button>Toggle</button>
</div>
<div class="box">
<p>{{content}}</p>
<div class="button-w">
<button>Close</button>
</div>
</div>
</section>
CSS
.button-w {
width: 100%;
float: left;
}
.box {
width: 100%;
border: 1px solid lime;
overflow: hidden;
color: white;
}
jQuery(速度.js)
var boxxHeight = $('.box').outerHeight();
$('.box').hide();
$('button').on('click', function() {
var boxx = $('.box');
if ( boxx.is(":visible") ) {
boxx.velocity({ opacity: 0, height: 0 }, { display: "none" });
} else {
boxx.velocity({ opacity: 1, height: boxxHeight }, { display: "block" });
}
});
有任何想法吗?
编辑
我真的没有任何真正的理由需要这些部分display: none
。这意味着我可以有一个带有溢出的外框:隐藏,并且内容将始终具有它的自然高度来检索和使用。
<div class="button-w">
<button>Toggle</button>
</div>
<div class="box">
<div class="inner-wrapper">
{{content}}
<div class="button-w">
<button>Close</button>
</div>
</div>
</div>
CSS
.box {
width: 100%;
overflow: hidden;
color: white;
padding: 1rem 0;
.inner-wrapper {
float: left;
opacity: 0;
padding-bottom: 5em;
background: white;
color: black;
padding: 1rem;
}
}
button {
display: block;
padding: 1rem;
border: 0;
&:focus {
outline: 0;
}
}
.hidden-box {
height: 0;
opacity: 0;
padding: 0;
.inner-wrapper {
opacity: 0;
}
}
jQuery(带有velocity.js)
通过将 .box 设置为 height:0 并使用 .hidden-box 类隐藏溢出来“隐藏” .inner-wrapper。存储 .inner-wrapper 的高度,并且高度动画仅发生在 .box 上 - 以及 .inner-wrapper 上的不透明度......
$('.box').addClass('hidden-box')
$('button').on('click', function() {
var vBoxx = $(this).closest('section').find('.box');
var vInner_wrapper = $(this).closest('section').find('.inner-wrapper');
var vElementHeight = vInner_wrapper.outerHeight();
if ( vBoxx.hasClass("hidden-box") ) {
vBoxx.velocity({
height: vElementHeight
}, {
duration: 500,
}).removeClass('hidden-box');
setTimeout( function() {
$(vInner_wrapper).velocity({opacity: 1});
},250);
} else {
$(vInner_wrapper).velocity({
opacity: 0
});
setTimeout( function() {
vBoxx.velocity({ height: 0 }).addClass('hidden-box');
},250);
}
});
在此处使用CodePen: