代码如下 |
复制代码 |
/**
* 跳转到指定元素的位置
* 使用方法
* scroller(el, duration)
* el : 目标锚点 ID
* duration : 持续时间,以毫秒为单位,越小越快
*/
var flutil = {
intval: function(v) {
v = parseInt(v);
return isNaN(v) ? 0 : v;
},
getPos: function(e) { // 获取元素信息
var l = 0;
var t = 0;
var w = this.intval(e.style.width);
var h = this.intval(e.style.height);
var wb = e.offsetWidth;
var hb = e.offsetHeight;
while (e.offsetParent) {
l += e.offsetLeft + (e.currentStyle ? this.intval(e.currentStyle.borderLeftWidth) : 0);
t += e.offsetTop + (e.currentStyle ? this.intval(e.currentStyle.borderTopWidth) : 0);
e = e.offsetParent;
}
l += e.offsetLeft + (e.currentStyle ? this.intval(e.currentStyle.borderLeftWidth) : 0);
t += e.offsetTop + (e.currentStyle ? this.intval(e.currentStyle.borderTopWidth) : 0);
return {
x: l,
y: t,
w: w,
h: h,
wb: wb,
hb: hb
};
},
getScroll: function() { // 获取滚动条信息
var t, l, w, h;
if (document.documentElement && document.documentElement.scrollTop) {
t = document.documentElement.scrollTop;
l = document.documentElement.scrollLeft;
w = document.documentElement.scrollWidth;
h = document.documentElement.scrollHeight;
} else if (document.body) {
t = document.body.scrollTop;
l = document.body.scrollLeft;
w = document.body.scrollWidth;
h = document.body.scrollHeight;
}
return {
t: t,
l: l,
w: w,
h: h
};
},
scroller: function(el, duration) { // 锚点(Anchor)间平滑跳转
if (typeof el != 'object') {
el = document.getElementById(el);
}
if (!el) return;
var z = this;
z.el = el;
z.p = this.getPos(el);
z.s = this.getScroll();
z.clear = function() {
window.clearInterval(z.timer);
z.timer = null
};
z.t = (new Date).getTime();
z.step = function() {
var t = (new Date).getTime();
var p = (t - z.t) / duration;
if (t >= duration + z.t) {
z.clear();
window.setTimeout(function() {
z.scroll(z.p.y, z.p.x)
}, 13);
} else {
st = ((-Math.cos(p * Math.PI) / 2) + 0.5) * (z.p.y - z.s.t) + z.s.t;
sl = ((-Math.cos(p * Math.PI) / 2) + 0.5) * (z.p.x - z.s.l) + z.s.l;
z.scroll(st, sl);
}
};
z.scroll = function(t, l) {
window.scrollTo(l, t)
};
z.timer = window.setInterval(function() {
z.step();
}, 13);
}
} |
|