首页 > 开发 > Javascript > 正文

js 居中漂浮广告

2020-02-28 04:03:54
字体:
来源:转载
供稿:网友
程序源码
代码如下:
var floatAd = {};
floatAd.getScrollTop = function(node) {
var doc = node ? node.ownerDocument : document;
return doc.documentElement.scrollTop || doc.body.scrollTop;
};
floatAd.getScrollLeft = function(node) {
var doc = node ? node.ownerDocument : document;
return doc.documentElement.scrollLeft || doc.body.scrollLeft;
};
floatAd.getBrowser = function() {
var d = document.documentElement;
return {
width: window.innerWidth || (d && d.clientWidth) || document.body.clientWidth,
height: window.innerHeight || (d && d.clientHeight) || document.body.clientHeight
}
};
floatAd.extend = function(destination, source) {
for(var property in source) {
destination[property] = source[property];
}
return destination;
};
/* 默认属性扩展 */
floatAd.setOptions = function(options) {
this.options = {
delay: 20, // 调整速率
fadeTime: 1 // 自动消失时间
};
return this.extend(this.options, options || {});
};
/* 类初始化 */
floatAd.init = function(id, options) {
var _this = this;
this.extend(this, this.setOptions(options));
this.control = document.getElementById(id);
var _callback = function() { // fadeIn完成后的回调函数
_this.timer = window.setInterval(function() { _this.scroll() }, _this.delay); // 滚动定位
window.setTimeout(function() { _this.fadeOut() }, _this.fadeTime * 1000); // 在固定时间内消失
}
this.fadeIn(_callback);
window.onresize = function() { _this.setCenter(); }
};
/* 定时滚动 */
floatAd.scroll = function() {
this.start = parseInt(this.control.style.top, 10);
this.end = parseInt(this.getScrollTop() + this.getBrowser().height - this.control.clientHeight, 10);
if(this.start != this.end) {
this.amount = Math.ceil(Math.abs(this.end - this.start) / 15); /* 递减公式(this.start无限增大,整个分子无限减小,整个值就无限趋近于0) */
this.control.style.top = parseInt(this.control.style.top, 10) + ((this.end < this.start) ? -this.amount : this.amount) + 'px';
}
};
/* 目标居中并处于最底部 */
floatAd.setCenter = function() {
this.top = this.getScrollTop() + floatAd.getBrowser().height;
this.left = (this.getScrollLeft() + floatAd.getBrowser().width - this.control.clientWidth) / 2;
this.control.style.top = this.top + 'px';
this.control.style.left = this.left + 'px';
};
/* fadeIn */
floatAd.fadeIn = function(callback) {
var _this = this, _top = 0;
this.control.style.display = 'block'; // *要提前显示.不然无法取得clientWidth
this.setCenter();
var _timer = window.setInterval(function() {
_this.control.style.top = _this.getScrollTop() + _this.getBrowser().height - (++_top) + 'px';
if(_top >= _this.control.clientHeight) {
window.clearInterval(_timer);
callback && callback();
}
}, 2);
};
/* fadeOut */
floatAd.fadeOut = function() {
var _this = this, _num = 0, _top = _this.control.clientHeight;
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表