Created
August 13, 2014 23:37
-
-
Save tanshio/039c5f136f2b72586f29 to your computer and use it in GitHub Desktop.
smoothscroll.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Math.ease = function (t, b, c, d) { | |
t /= d/2; | |
if (t < 1) return c/2*t*t*t + b; | |
t -= 2; | |
return c/2*(t*t*t + 2) + b; | |
}; | |
function smoothScroll(hash){ | |
var date = new Date(), | |
pos = document.body.scrollTop, | |
_time, | |
end = document.getElementById(hash.split('#')[1]).offsetTop, | |
plus; | |
if(992 > window.innerWidth){ | |
plus = 70; | |
}else{ | |
plus = 0; | |
} | |
end -= plus; | |
function time(){ | |
var now = new Date(), | |
duration = 1500; | |
if(now-date<1500){ | |
_time = setTimeout(function(){ | |
var scroll = Math.ease(now-date,pos,end-pos,duration); | |
window.scrollTo(0,parseInt(scroll,10)); | |
time(); | |
},0); | |
}else{ | |
clearTimeout(_time); | |
} | |
} | |
time(); | |
} | |
Array.prototype.forEach.call(document.querySelectorAll('a'),function(node){ | |
node.addEventListener('click', function(e){ | |
e.preventDefault(); | |
if(e.target.getAttribute('data-tabs')||e.target.getAttribute('data-imagelightbox')||e.target.parentNode.getAttribute('data-imagelightbox')){ | |
//data-tabs要素、data-imagelightboxに何かあったら処理しない | |
return; | |
} | |
var linkTo = e.target.href, | |
thisURL = e.target.baseURI; | |
if(!linkTo){ | |
//hrefがなかったらある親まで遡る | |
var parent = e.target.parentNode; | |
while(parent.localName!=='a'){ | |
parent = parent.parentNode; | |
} | |
linkTo = parent.href; | |
} | |
if(thisURL===linkTo.split('#')[0] && e.target.hash.length>1){ | |
//現在のURLかつハッシュがあったらアンカーまで飛ばす | |
// location.href=linkTo; | |
if(document.getElementById(e.target.hash)){ | |
//ハッシュ値がおかしい場合はストップ | |
return; | |
} | |
smoothScroll(e.target.hash); | |
}else{ | |
location.href=linkTo; | |
} | |
}, false); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment