代碼來自慕課網教程
function starMove(obj, attr, target) {
clearInterval(obj.timer);
obj.timer = setInterval(function () {
var incur = parseInt(getStyle(obj, attr));
var speed = (target - incur) / 10;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed)
if (incur == target) {
clearInterval(obj.timer);
}
else {
obj.style[attr] = incur + speed + 'px';
}
}, 30)
}
function getStyle(obj, attr) {
if (obj.currentStyle) {
return obj.currentStyle[attr];
}
else{
return getComputedStyle(obj,false)[attr];
}
}
這並不是最完美的框架因爲還沒有加入對透明度的兼容性以及鏈式反應
框架要點
先獲得需要改變的對象和JS中CSS的屬性名
先清楚已經在這個Obj上的計時器(防止多次移入鼠標時計時器疊加)
通過getstyle方法獲得當前屬性的靜態屬性
然後計算速度:如果目標大於當前屬性位置,則速度爲正,並用Math.ceil()方法將向上round爲整數以便瀏覽器能夠繼續計算他的屬性值(因爲瀏覽器不接受小數的像素值),反之速度爲負,用Math.floor()函數
然後判斷,如果當前屬性位置已經到達target則清除計時,如果沒有達到,則通過obj.style獲取當前屬性並更新屬性值