同一頁面多個元素,各自綁定不同屬性動畫(寬度、高度、字號、透明度),互不干擾,同時運行。
function getStyle(el, prop) {
return el.currentStyle ? el.currentStyle[prop] : getComputedStyle(el, false)[prop];
}
function startRun(el, attr, target) {
clearInterval(el.timer); // 每元素獨立 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);
} 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);
}
<style>
#runs li { width: 80px; height: 80px; background: #06c; list-style: none; margin: 10px; border: 1px solid #000; filter: alpha(opacity=30); opacity: 0.3; }
</style>
<ul id="runs">
<li style="top:0">1</li>
<li style="top:90px">2</li>
<li style="top:180px">3</li>
<li style="top:270px">4</li>
</ul>
<script>
window.onload = function() {
var items = document.getElementById('runs').getElementsByTagName('li');
items[0].onmouseover = function() { startRun(this, 'width', 300); };
items[0].onmouseout = function() { startRun(this, 'width', 80); };
items[1].onmouseover = function() { startRun(this, 'height', 300); };
items[1].onmouseout = function() { startRun(this, 'height', 80); };
items[2].onmouseover = function() { startRun(this, 'fontSize', 50); };
items[2].onmouseout = function() { startRun(this, 'fontSize', 14); };
items[3].onmouseover = function() { startRun(this, 'opacity', 100); };
items[3].onmouseout = function() { startRun(this, 'opacity', 30); };
};
</script>
el.timer 掛在元素上,互不衝突。opacity 用 parseFloat * 100 + Math.round,其它用 parseInt 去單位。(target - cur) / 8 形成越來越慢的緩動效果,ceil/floor 保證能到達終點。el.style[attr] 動態設置,支援駝峰屬性名(fontSize)。function animateMulti(el, props, duration, easing, cb) {
// props: {width: 300, opacity: 100, ...}
// 內部為每屬性創建獨立定時器或用 rAF 統一幀循環
}
實戰建議封裝為類,管理動畫隊列、暫停/恢復、完成回調。