想讓留言區或評論框更有互動感?給使用者一組「放大、縮小、向上、向下」的控制鈕是個不錯的小巧思。研究了這段程式碼,會發現它比想像中簡單。
$(function(){
var $comment = $('#comment');
$('.bigger').click(function(){
if(!$comment.is(":animated")){
if($comment.height() < 500){
$comment.animate({height:"+=50"}, 400);
}
}
});
$('.smaller').click(function(){
if(!$comment.is(":animated")){
if($comment.height() > 50){
$comment.animate({height:"-=" 50}, 400);
}
}
});
$('.up').click(function(){
if(!$comment.is(":animated")){
$comment.animate({scrollTop:"-=50"}, 400);
}
});
$('.down').click(function(){
if(!$comment.is(":animated")){
$comment.animate({scrollTop:"+=50"}, 400);
}
});
});
兩個設計細節值得注意:一是用 :animated 判斷避免動畫尚未結束就被連續觸發,導致高度跳來跳去;二是用 "+=50" 這種相對值寫法,不必每次都去讀取目前高度再計算。
<div class="msg">
<div class="msg_caption">
<span class="bigger">放大</span>
<span class="smaller">縮小</span>
<span class="up">向上</span>
<span class="down">向下</span>
</div>
<div>
<textarea id="comment" rows="8" cols="20">
這裡放入多行文字內容,方便測試捲動效果……
</textarea>
</div>
</div>
.bigger , .down , .up , .smaller{
background-color: #f1a55c;
}
程式碼就到這裡,至於要用在何處、怎麼搭配自己的樣式,就留給各位自由發揮了。實務上還可以補一個高度上限提示,讓使用者知道已經放到最大。