這個效果常見於企業網站頂部:一條工具列平時收在頁面外,滑鼠移過去才滑下來,移開後再收回。核心是一個自製的缓動位移函式。
<!DOCTYPE html>
<html>
<head>
<title>可以折疊的菜單工具列</title>
<style>
html, body { margin: 0; }
body { background: url(img.jpg) repeat-x; }
img { border: none; }
#fx_topToolbar {
position: relative;
top: -76px;
left: 0;
margin: 0 auto;
height: 92px;
background: #0C3E74;
width: 700px;
text-align: center;
}
#fx_topToolbar .shell {
margin: 0 auto;
padding: 13px 0;
}
#btn_offOn {
position: absolute;
bottom: -8px;
left: 20px;
height: 24px;
width: 150px;
background: url(img34.gif) no-repeat;
}
#btn_offOn a {
display: block;
zoom: 1;
height: 24px;
position: relative;
right: -16px;
background: url(tip.gif) no-repeat 100% 0;
}
</style>
<script>
var JS = {
$: function (o) {
return typeof o == "string" ? document.getElementById(o) : o;
},
on: function (o, type, fn) {
o.attachEvent
? o.attachEvent('on' + type, function () { fn.call(o); })
: o.addEventListener(type, fn, false);
return JS.on;
},
// 缓動位移:attr 為要動的樣式,val 為目標值,s 為速度係數
move: function (who, attr, val, s, fn) {
var fm = parseInt(who.style[attr]) || 0;
clearInterval(who['timer_' + attr]);
var iFx = (function (form, to, s) {
return function () {
// 每次走「剩餘距離 × 速度係數」,形成先快後慢的緩衝
return form += Math[form < to ? 'ceil' : 'floor']((to - form) * (s || 0.3));
};
})(fm, val, s);
who['timer_' + attr] = setInterval(function () {
var v = iFx();
who.style[attr] = v + 'px';
if (v == val) {
fn && fn.call(who);
clearInterval(who['timer_' + attr]);
}
}, 18);
}
};
JS.on(window, 'load', function () {
var Q = JS.$('fx_topToolbar');
Q.style.top = '-74px';
JS.on(JS.$('btn_offOn'), 'mouseover', function () {
JS.move(Q, 'top', 0); // 滑入:展開
});
JS.on(Q, 'mouseout', function () {
// 延遲 10ms 再收,避免滑過內部元素時誤觸
Q.outTimer = setTimeout(function () {
JS.move(Q, 'top', -74);
}, 10);
});
JS.on(Q, 'mouseover', function () {
clearTimeout(this.outTimer); // 回到工具列上則取消收合
});
});
</script>
</head>
<body>
<div id="fx_topToolbar">
<div class="shell">
<a href="#" title=""><img src="1.gif" width="231" height="58" alt="" /></a>
<a href="#" title=""><img src="2.gif" width="231" height="58" alt="" /></a>
</div>
<div id="btn_offOn"><a href="#" title=""></a></div>
</div>
</body>
</html>
form += Math.ceil((to - form) * s)。每次都只走剩餘距離的固定比例,越接近目標走得越慢,這是所有手寫缓動動畫的核心公式。
#toolbar {
position: fixed;
top: 0;
left: 50%;
transform: translate(-50%, -76px);
height: 92px;
background: #0C3E74;
transition: transform 0.4s cubic-bezier(0.22, 1, 0.36, 1);
}
#toolbar:hover,
#toolbar.open {
transform: translate(-50%, 0);
}
</style>
用 transform: translateY() 取代動 top,動畫交由合成器處理,不會觸發重排,順度明顯更好。:hover 也能省掉大部分 JavaScript。
aria-expanded 標示狀態)。:focus-within 時同樣展開。scroll-padding-top 或 body 的 padding-top,以免遮住頁面標題。<img> 帶有空 alt,對螢幕閱讀器而言是裝飾性圖片;若圖片本身承載連結意義,應補上描述性 alt 文字。