「滑鼠移上去,元素慢慢變亮;移開,慢慢變暗」——這個效果看起來柔和,實作起來也很單純,本質上就是一個定時器加上方向判斷。
元素初始透明度為 30,滑鼠移上時透明度逐步遞增直到 100 停止;滑鼠移出時再逐步遞減回到 30。
要點一:用變數當「看不見的透明度」。CSS 沒辦法直接遞增 opacity,所以把當前值存在變數裡,讓變數變化,最後再把變數寫回元素的樣式。
var alpha = 30;
要點二:比較目標值與目前值,決定速度方向。目標比現在大就走正向,反之走負向。
if (target > alpha) {
speed = 2;
} else {
speed = -2;
}
要點三:到達目標就收工,否則繼續走。收工前把值寫回元素。由於 opacity 有相容問題,IE 的 filter 寫法也要一起寫上。
if (alpha == target) {
clearInterval(timer);
} else {
alpha = alpha + speed;
run.style.filter = 'alpha(opacity=' + alpha + ')';
run.style.opacity = alpha / 100;
}
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>透明度漸變</title>
<style>
body { margin:0; padding:0; }
#run {
width:100px; height:100px; background:#06c; position:absolute;
border:1px solid #000; opacity:0.3; filter:alpha(opacity=30);
}
</style>
<script>
window.onload = function () {
var run = document.getElementById("run");
var speed = 1;
var timer = null;
var alpha = 30;
run.onmouseover = function () { startrun(100); };
run.onmouseout = function () { startrun(30); };
function startrun(target) {
clearInterval(timer);
timer = setInterval(function () {
if (target > alpha) { speed = 2; } else { speed = -2; }
if (alpha == target) {
clearInterval(timer);
} else {
alpha = alpha + speed;
run.style.filter = 'alpha(opacity=' + alpha + ')';
run.style.opacity = alpha / 100;
}
}, 30);
}
};
</script>
</head>
<body>
<div id="run"></div>
</body>
</html>
實作上有兩個細節值得留意:每次 startrun 開頭都要先 clearInterval,否則快速來回移動滑鼠會堆出一堆定時器互相打架;另外,alpha == target 這種嚴格相等判斷要求兩邊剛好都是偶數或奇數,若把 speed 改成 3 或 5 就可能永遠碰不到目標值而無限循環——改成 alpha >= target 這類區間判斷會更穩健。