insertBefore(new, firstChild) 實現置頂插入offsetHeight 獲取實際高度,先置 0 再動畫startRun(el, attr, target, callback) 支援鏈式調用getComputedStyle / currentStyle 兼容獲取當前樣式值<!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>
</head>
<body>
<textarea id="con" cols="50" rows="5"></textarea>
<input id="btn" type="button" value="發布">
<ul id="list"></ul>
<script>
window.onload = function() {
var btn = document.getElementById('btn');
var con = document.getElementById('con');
var list = document.getElementById('list');
btn.onclick = function() {
var text = con.value.trim();
if (!text) return;
con.value = '';
var li = document.createElement('li');
li.innerHTML = text;
li.style.height = '0'; // 初始高度 0
// 置頂插入
var first = list.getElementsByTagName('li')[0];
first ? list.insertBefore(li, first) : list.appendChild(li);
// 獲取實際高度(需先加入文檔流才能測量)
var targetH = li.offsetHeight;
li.style.height = '0';
// 階段1:高度展開 → 階段2:透明度淡入
startRun(li, 'height', targetH, function() {
startRun(li, 'opacity', 100);
});
};
};
// 通用緩動動畫引擎
function getStyle(el, prop) {
return el.currentStyle ? el.currentStyle[prop] : getComputedStyle(el, false)[prop];
}
function startRun(el, attr, target, cb) {
clearInterval(el.timer);
el.timer = setInterval(function() {
var cur = attr === 'opacity'
? Math.round(parseFloat(getStyle(el, attr)) * 100)
: parseInt(getStyle(el, attr));
var speed = (target - cur) / 8;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (cur === target) {
clearInterval(el.timer);
cb && cb();
} else {
if (attr === 'opacity') {
el.style.filter = 'alpha(opacity=' + (cur + speed) + ')';
el.style.opacity = (cur + speed) / 100;
} else {
el.style[attr] = cur + speed + 'px';
}
}
}, 30);
}
</script>
</body>
</html>
<style>
#list li { transition: height .3s ease, opacity .3s ease .3s; opacity: 0; height: 0; overflow: hidden; }
#list li.show { height: auto; opacity: 1; } /* height:auto 無法過渡,見下文 */
</style>
<script>
btn.onclick = function() {
var li = document.createElement('li');
li.textContent = con.value.trim(); con.value = '';
if (!text) return;
var first = list.querySelector('li');
first ? list.insertBefore(li, first) : list.appendChild(li);
// 強制回流讀取高度
var h = li.scrollHeight;
li.style.height = h + 'px'; // 顯式高度可過渡
li.style.opacity = 1;
// 動畫結束後改為 auto 防止內容變化截斷
li.addEventListener('transitionend', function fn() {
li.style.height = 'auto';
li.removeEventListener('transitionend', fn);
});
};
</script>
注意:CSS 無法直接過渡 height: 0 → auto,需用 JS 測量後設定具體像素值,動畫結束再改回 auto。