引入 jquery.js 之後,把下面的程式碼貼進頁面就能跑。這裡示範四種方向的滑動:由下往上、改變寬度、改變 left、改變 marginLeft。
<style type="text/css">
.slide {
position: relative;
height: 200px;
background-color: lightyellow;
}
.slide .inner {
position: absolute;
left: 0;
bottom: 0;
height: 100px;
width: 100%;
background-color: lightblue;
}
</style>
slideToggle() 會在 slideDown() 與 slideUp() 之間交替,是最省事的做法。
<div id="slidebottom" class="slide"> <button>slide it</button> <div class="inner">Slide from bottom</div> </div>
$('#slidebottom button').click(function () {
$(this).next().slideToggle();
});
<div id="slidewidth" class="slide"> <button>slide it</button> <div class="inner">Slide from left</div> </div>
$("#slidewidth button").click(function () {
$(this).next().animate({ width: 'toggle' });
});
這一版不隱藏元素,而是真的把它推出去。
<div id="slideleft" class="slide" style="width: 50%; float: right"> <button>slide it</button> <div class="inner">Slide from left</div> </div>
$("#slideleft button").click(function () {
var $lefty = $(this).next();
$lefty.animate({
left: parseInt($lefty.css('left'), 10) == 0 ? -$lefty.outerWidth() : 0
});
});
<div id="slidemarginleft" class="slide" style="width: 60%; float: left"> <button>slide it</button> <div class="inner">Slide from right</div> </div>
$("#slidemarginleft button").click(function () {
var $marginlefty = $(this).next();
$marginlefty.animate({
marginLeft: parseInt($marginlefty.css('marginLeft'), 10) == 0 ? $marginlefty.outerWidth() : 0
});
});
slideToggle 只走垂直方向。jQuery 內建的 slideDown/slideUp/slideToggle 都是動 height,想做水平滑動必須自己用 animate() 改 width 或邊界屬性。
用 outerWidth() 而不是 width()。第 3、4 個範例要計算「完全移出視線」需要多遠,outerWidth() 含 padding 與 border,算起來才準。
parseInt 一定要帶第二個參數 10。parseInt($el.css('left'), 10) 明確指定十進位,避免少見的字串前綴造成誤判;同時 css() 回傳的是 "0px" 這類字串,不轉數字無法比較。
用三元運算子做開關。判斷目前是否為 0 來決定要滑出還是滑回,比維護一個額外的布林狀態變數更簡潔。