頁面載入 3 秒後,右側自動滑入浮動廣告條;點擊標籤可手動展開/收合;展開超過設定時長(10 秒)自動收合;捲動頁面時廣告條固定於視窗右側跟隨。
var CLS = {
create: function() {
return function() {
this.$ADD = function(fn) { CLS.add(this, fn); };
this.init.apply(this, arguments);
};
},
add: function(obj, fn) { fn.apply(obj, Array.prototype.slice.call(arguments, 2)); },
enterFrame: function() {
this.onEnterFrame = function() {};
this.$PLAY = function(delay) {
this.enterFrameP = this.enterFrameP || 10;
this.CLStimeIndex = CLS.ontimes.length;
CLS.ontimes.push(this);
clearTimeout(this.enterFrameTimeout); clearInterval(this.enterFrameInterval);
if (delay) this.enterFrameTimeout = setTimeout('CLS.ontimes[' + this.CLStimeIndex + '].enterFrameInterval=setInterval("CLS.ontimes[' + this.CLStimeIndex + '].onEnterFrame()",' + this.enterFrameP + ')', delay * 1000);
else this.enterFrameInterval = setInterval('CLS.ontimes[' + this.CLStimeIndex + '].onEnterFrame()', this.enterFrameP);
};
this.$STOP = function() { clearInterval(this.enterFrameInterval); };
this.$SET = function(p) { this.enterFrameP = p; };
},
ontimes: []
};
CLS.Marquee = CLS.create();
CLS.Marquee.prototype = {
init: function(btnId, boxId, speed) {
this.box = $(boxId); this.tit = $(btnId); this.kong = $('kong');
this.onOpen = true; this.show = false; this.time = 0; this.speed = speed;
this.Maxw = this.box.offsetWidth - this.tit.offsetWidth;
this.box.style.right = -this.box.offsetWidth + 'px';
this.boxTop = this.kong.offsetTop;
var _t = this;
this.tit.onclick = function() {
this.show = true;
if (_t.onOpen) { _t.onEnterFrame = _t.close; _t.onOpen = false; }
else { _t.onEnterFrame = _t.open; _t.onOpen = true; }
_t.$PLAY();
};
this.$ADD(CLS.enterFrame);
this.onEnterFrame = this.open;
this.$PLAY();
},
open: function() {
this.tit.innerHTML = '-';
var r = parseInt(this.box.style.right);
var step = (0 - r) / 30; // 緩入
this.box.style.right = (r + step) + 'px';
this.kong.style.top = (document.documentElement.scrollTop + this.boxTop) + 'px';
if (step === 0 && !this.show) {
this.time += 10;
if (this.time >= this.speed * 1000) {
this.show = true; this.onOpen = false; this.$STOP();
this.onEnterFrame = this.close; this.$PLAY();
}
}
},
close: function() {
this.tit.innerHTML = '+';
var r = parseInt(this.box.style.right);
var step = (-this.Maxw - r) / 5; // 緩出
this.box.style.right = Math.round(r + step) + 'px';
this.kong.style.top = (document.documentElement.scrollTop + this.boxTop) + 'px';
}
};
window.onload = function() {
setTimeout(function() { new CLS.Marquee('tit', 'abc', 10); }, 3000);
};
CLS.ontimes 陣列管理所有動畫實例,統一 setInterval 驅動。(目標 - 當前) / 系數 形成指數衰減曲線,視覺自然。kong 佔位元素 top = scrollTop + 初始top 實現 position:fixed 效果(舊 IE 不支援 fixed)。open 狀態計時達 speed*1000 自動切換 close。