【发布时间】:2014-06-20 08:57:14
【问题描述】:
我正在尝试使用velocity.js 制作类似slideToggle() 方法的滑动切换淡入淡出动画 - 希望它会更流畅。
因为我无法滚动到 auto - 我将高度放在变量中并使用它来设置高度的动画。我遇到的问题是高度值存储一次,如果页面稍微调整大小,则数字不再正确。 - 另外 - 因为该区域在页面加载时被隐藏,(在它获得初始高度之后)我无法再次检查高度(如果发生窗口大小调整)
最后我想把它放到一个函数中,所以保持相对它的关键。
另外,如果你没有使用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 (velocity.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 HERE:
【问题讨论】:
-
找到解决问题的方法?
-
几乎,但还没有处理所有的边缘情况。
标签: javascript jquery animation velocity.js