[JS]テキストの一部のみ最初に表示し、残りをアニメーションで表示するスクリプト
Post on:2010年12月14日
sponsorsr
パネルに配置したテキストを下部にいくにつれフェードアウトで表示し、残りのテキストをアニメーションで表示するコンテンツを実装するチュートリアルを紹介します。

Text Fade Out / Read More Link
デモページ
[ad#ad-2]
デモでは3つのサンプルが用意されています。

テキストの冒頭のみが表示された状態のキャプチャ
それぞれ「Read More」をクリックすると、残りのテキストがアニメーションで表示されます。

残りのテキストをアニメーションで表示したキャプチャ
[ad#ad-2]
実装
HTML
HTMLはシンプルで、テキストと「Read More」ボタンをdiv要素内に配置します。
<div class="sidebar-box"> <p>パネルのテキスト</p> <p class="read-more"><a href="#" class="button">Read More</a></p> </div>
CSS
パネルの初期状態のサイズはスタイルシートで設定します。フェードアウトはCSS3グラデーションを使用します。
.sidebar-box {
max-height: 120px;
position: relative;
overflow: hidden;
}
.sidebar-box .read-more {
position: absolute;
bottom: 0; left: 0;
width: 100%;
text-align: center;
margin: 0; padding: 30px 0;
/* "transparent" only works here because == rgba(0,0,0,0) */
background-image: -moz-linear-gradient(top, transparent, black);
background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0, transparent),color-stop(1, black));
}
JavaScript
フェードアウトした残りのテキストをアニメーションで表示するのはjQueryをベースとしたものを使用します。
「jquery.js」を外部ファイルとして、下記のスクリプトを記述します。
var $el, $ps, $up, totalHeight;
$(".sidebar-box .button").click(function() {
totalHeight = 0
$el = $(this);
$p = $el.parent();
$up = $p.parent();
$ps = $up.find("p:not('.read-more')");
// measure how tall inside should be by adding together heights of all inside paragraphs (except read-more paragraph)
$ps.each(function() {
totalHeight += $(this).outerHeight();
});
$up
.css({
// Set height to prevent instant jumpdown when max height is removed
"height": $up.height(),
"max-height": 9999
})
.animate({
"height": totalHeight
});
// fade out read-more
$p.fadeOut();
// prevent jump-down
return false;
});
グラデーションと不透明度のメモ
グラデーションに不透明度を設定する時は、RGBaで指定を行った方がより正確なカラーを表現します。
例えば、blackではなく「0,0,0,0」、redではなく「255,0,0,0」にします。
background-image: -webkit-gradient( linear, left top, left bottom, color-stop(0, rgba(255,0,0,0)), color-stop(1, rgba(255,0,0,100)));
sponsors











