スライドアニメーション自体は、javascriptのすべてのアニメーションと同様に、タイマー関数setTimeout
またはを使用して実行されsetInterval
ます。このような単純な効果の場合setTimeout
、アニメーションシーケンスを終了する方がに比べて簡単なので、私は常に好みsetInterval
ます。仕組みは、以下を使用してCSS属性値を変更することですsetTimeout
。
// move the content div down 200 pixels:
var content = document.getElementById('content');
function moveDown () {
var top = parseInt(content.style.marginTop); // get the top margin
// we'll be using this to
// push the div down
if (!top) {
top = 0; // if the margin is undefined, default it to zero
}
top += 20; // add 20 pixels to the current margin
content.style.marginTop = top + 'px'; // push div down
if (top < 200) {
// If it's not yet 200 pixels then call this function
// again in another 100 milliseconds (100 ms gives us
// roughly 10 fps which should be good enough):
setTimeout(moveDown,100);
}
}
これが基本的にJavaScriptのアニメーションの基本です。アイデアはとてもシンプルです。アニメーションには任意のCSSスタイル属性を使用できます。絶対的または相対的に配置された要素の上下、私の例のような余白、幅、高さ、透明度などです。
さて、あなたの特定の場合に何を使うかは、あなたの意図が正確に何であるかに依存します。たとえば、説明する最も簡単な方法は、divの高さがゼロになるまで変更することです。何かのようなもの:
function collapseContent () {
var height = parseInt(content.style.height);
if (!height) {
height = content.offsetHeight; // if height attribute is undefined then
// use the actual height of the div
}
height -= 10; // reduce height 10 pixels at a time
if (height < 0) height = 0;
content.style.height = height + 'px';
if (height > 0) {
// keep doing this until height is zero:
setTimeout(collapseContent,100);
}
}
しかし、それはサンプルのjQueryプラグインが行う方法ではありません。上下のスタイル属性をシフトすることで要素を移動し、コンテナdivを使用してコンテンツを画面外に非表示にするように見えますoverflow:hidden
。