本文示範如何點擊按鈕讓一個 DIV 層以帶有「彈性」的手感滑向目標位置,由於每帧位移會依距離衰減,移動過程會有先快後慢、微微回彈的效果。完整程式碼如下:
代碼如下:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>點擊按鈕讓DIV層彈性移動特效</title>
<style type="text/css">
#div1{ background: #FFCC66; border:#FF6600 1px solid; height:100px; width:100px; position:relative; left:0px;}
</style>
<script type="text/javascript">
var t=null;
function startMove()
{
if(t)
{
clearInterval(t);
}
t=setInterval(move, 30);
}
var step=0;
function move()
{
var odiv=document.getElementById("div1");
step+=(100-odiv.offsetLeft)/50;
step=step*0.98
odiv.style.left=odiv.offsetLeft+step+"px";
}
</script>
</head>
<body>
<div id="div1">
</div>
<input type="button" value="移動" onclick="startMove()"/>
</body>
</html>
關鍵在 move 函式:每次把「目標值減目前值」除以 50 累加到步長 step,再乘上 0.98 做衰減,如此每帧位移會隨接近目標而變小,形成自然的緩動與彈性手感;以 setInterval 每 30 毫秒觸發一次。這正是所謂「緩動公式」的基礎寫法。希望本文對你的 JavaScript 開發有所幫助。