微博、論壇這類信息流產品有個共同細節:發布新內容後,這條內容會從列表頂部「長」出來,高度由零展開,同時透明度漸漸變清晰。整個過程不到半秒,卻讓人感覺頁面是活的。下面用原生 JS 復刻這個效果。
if (list_li.length >= 1) {
list.insertBefore(li, list_li[0]);
} else {
list.appendChild(li);
}
列表已有內容時插入到首個節點之前,否則直接追加。
var height = li.offsetHeight;
li.style.height = '0';
必須先取得元素在正常流中的真實高度,再把高度置為 0,這樣後面才有「從 0 到 height」的變化空間。
startrun(li, "height", height, function () {
startrun(li, "opacity", "100");
});
先展開高度,高度動畫結束後再讓透明度漸顯。
<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312" />
<title>新內容漸顯效果</title>
<style>
body, ul, li { margin:0; padding:0; font:12px/1.5 arial; }
#list { width:400px; margin:10px auto; }
#list li {
list-style:none; padding:5px 0; overflow:hidden;
border-bottom:1px dotted #ccc;
filter:alpha(opacity:0); opacity:0;
vertical-align:middle;
}
</style>
<script>
window.onload = function () {
var btn = document.getElementById("btn");
var con = document.getElementById("con");
var list = document.getElementById("list");
var list_li = list.getElementsByTagName("li");
btn.onclick = function () {
var li = document.createElement("li");
li.innerHTML = con.value;
con.value = '';
if (list_li.length >= 1) {
list.insertBefore(li, list_li[0]);
} else {
list.appendChild(li);
}
var height = li.offsetHeight;
li.style.height = '0';
startrun(li, "height", height, function () {
startrun(li, "opacity", "100");
});
};
};
function getstyle(obj, name) {
if (obj.currentStyle) {
return obj.currentStyle[name];
} else {
return getComputedStyle(obj, false)[name];
}
}
function startrun(obj, attr, target, fn) {
clearInterval(obj.timer);
obj.timer = setInterval(function () {
var cur = 0;
if (attr == "opacity") {
cur = Math.round(parseFloat(getstyle(obj, attr)) * 100);
} else {
cur = parseInt(getstyle(obj, attr));
}
var speed = (target - cur) / 8;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (cur == target) {
clearInterval(obj.timer);
if (fn) { fn(); }
} else {
if (attr == "opacity") {
obj.style.filter = "alpha(opacity=" + (cur + speed) + ")";
obj.style.opacity = (cur + speed) / 100;
} else {
obj.style[attr] = cur + speed + "px";
}
}
}, 30);
}
</script>
</head>
<body>
<textarea id="con" cols="50" rows="5"></textarea>
<input id="btn" type="button" value="發布" />
<ul id="list"></ul>
</body>
</html>
這裡的速度公式 (target - cur) / 8 就是緩衝運動的核心:距離越近步長越小,看起來會有自然的「減速收尾」感覺。透明度之所以要乘除 100,是因為要兼容 IE 的 filter 表達式。