코드 복사 코드는 다음과 같습니다. 用 Javascript 实现锚点(Anchor)间平滑跳转 <br> // 说明 :用 Javascript 实现锚点(Anchor)间平滑跳转 <br> <br> // 转换为数字 <br> function intval(v) <br> { <br> v = parseInt(v); <br> return isNaN(v) ? 0 : v; <br> } <br> // 获取元素信息 <br> function getPos(e) <br> { <br> var l = 0; <br> var t = 0; <br> var w = intval(e.style.width); <br> var h = intval(e.style.height); <br> var wb = e.offsetWidth; <br> var hb = e.offsetHeight; <br> while (e.offsetParent) <br> { <br> l += e.offsetLeft + (e.currentStyle?intval(e.currentStyle.borderLeftWidth):0); <br> t += e.offsetTop + (e.currentStyle?intval(e.currentStyle.borderTopWidth):0); <br> e = e.offsetParent; <br> } <br> l += e.offsetLeft + (e.currentStyle?intval(e.currentStyle.borderLeftWidth):0); <br> t += e.offsetTop + (e.currentStyle?intval(e.currentStyle.borderTopWidth):0); <br> return {x:l, y:t, w:w, h:h, wb:wb, hb:hb}; } <br> // 获取滚动条信息 <br> function getScroll() <br> { <br> var t, l, w, h; <br> if (document.documentElement && document.documentElement.scrollTop) <br> { <br> t = document.documentElement.scrollTop; <br> l = document.documentElement.scrollLeft; <br> w = document.documentElement.scrollWidth; <br> h = document.documentElement.scrollHeight; <br> } <br> else if (document.body) <br> { <br> t = document.body.scrollTop; <br> l = document.body.scrollLeft; <br> w = document.body.scrollWidth; <br> h = document.body.scrollHeight; <br> } <br> return { t: t, l: l, w: w, h: h }; <br> } <br> // 锚点(Anchor)间平滑跳转 <br> function scroller(el, duration) <br> { <br> if(typeof el != 'object') <br> { <br> el = document.getElementById(el); <br> } <br> if(!el) return; <br> var z = this; <br> z.el = el; <br> z.p = getPos(el); <br> z.s = getScroll(); <br> z.clear = function() <br> { <br> window.clearInterval(z.timer);z.timer=null <br> }; <br> z.t=(new Date).getTime(); <br> z.step = function() <br> { <br> var t = (new Date).getTime(); <br> var p = (t - z.t) / duration; <br> if (t >= duration + z.t) <br> { <br> z.clear(); <br> window.setTimeout(function(){z.scroll(z.p.y, z.p.x)},13); } <br> else { <br> st = ((-Math.cos(p*Math.PI)/2) + 0.5) * (z.p.y-z.s.t) + z.s.t; <br> sl = ((-Math.cos(p*Math.PI)/2) + 0.5) * (z.p.x-z.s.l) + z.s.l; <br> z.scroll(st, sl); <br> } <br> }; <br> z.scroll = function (t, l){window.scrollTo(l, t-20)}; <br> z.timer = window.setInterval(function(){z.step();},13); <br> } <br> <br> div.test <br> { <br> width:400px; margin:5px auto; border:1px solid #ccc; <br> } <br> div.test strong <br> { font-size:16px; background:#fff; border-bottom:1px solid #aaa; margin:0; display:block; padding:5px 0; text-decoration:underline; color:#059B9A; cursor:pointer; } div.test p { height:400px; background:#f1f1f1; margin:0; <br> } <br> header_1 --> header_4 header_2 --> header_5 header_3 --> header_6 header_4 --> header_7 header_5 --> header_3 header_6 --> header_2 header_7 --> header_1