앵커(anchor)스무스하게 움직이게 하기
js
function goTop(orix,oriy,desx,desy) {
var Timer;
var winHeight = document.body.scrollHeight;
if(Timer) clearTimeout(Timer);
startx = 0;
starty = winHeight;
if(!orix || orix < 0) orix = 0;
if(!oriy || oriy < 0) oriy = 0;
var speed = 10; // 숫자가 낮을 수록 빨리 움직인다.
if(!desx) desx = 0 + startx;
if(!desy) desy = 0 + starty;
desx += (orix - startx) / speed;
if (desx < 0) desx = 0;
desy += (oriy - starty) / speed;
if (desy < 0) desy = 0;
var posX = Math.ceil(desx);
var posY = Math.ceil(desy);
console.log('pos', posX, posY);
window.scrollTo(posX, posY);
if((Math.floor(Math.abs(startx - orix)) < 1) && (Math.floor(Math.abs(starty - oriy)) < 1)){
clearTimeout(Timer);
window.scroll(orix,oriy);
}else if(posX != orix || posY != oriy){
Timer = setTimeout("goTop("+orix+","+oriy+","+desx+","+desy+")", 100);
}else{
clearTimeout(Timer);
}
}
css
.anchor-div {
padding-top: 500px;
}
html
<span> i am top</span>
<div class="anchor-div">
<a href="#top" onclick="goTop(); return false;" onfocus="blur()"> goto top </a>
</div>
See the Pen anchor 스무스 하게 움직이기 by younghyeong ryu (@wangta69) on CodePen.