說明
- 設定好自訂動畫函數,input固定間隔值的數字,動畫函數的output會是一個動畫曲線
- 用setInterval寫動畫執行函數。參數意義如下
ele:element
b:before(初期值)
c:change(終點值)
t:timing(目前的時間戳)
d:duration(這個動畫總共要有幾秒)
.box
.box
.box
.box
.box
.box
.box
.box
.box
.box
.box
.box
.box
.box
.box
.box
.box
.box
.box
.box
button(onclick="move()") click me
.box
background: teal
width: 200px
height: 100px
margin: 40px
//easing函數
function easeOut(t, d){
return 1 - Math.pow(1-(t/d), 5);
}
function smoothScroll(ele, b){
var c=-ele.scrollTop;
var start = Date.now();
var total = 1400; //毫秒
var d = 1;
timer = window.setInterval(function() {
var t = (Date.now() - start) / total;
var result = easeOut(t, d);
var y = b + result * c;
ele.scrollTop = y;
if (t >= d) {
clearInterval(timer);
}
}, 16);
}
function move(){
if(document.body.scrollTop!==0){
//Safari
smoothScroll(document.body, pageYOffset)
}else{
//Chrome, FF, IE
smoothScroll(document.documentElement, pageYOffset)
}
}
easing 函數介紹
easing out類(開始快,結束慢)
easing out by pow (指數)
function easeOutPow(t, d){
return 1 - Math.pow(1-(t/d), 5);
}
easing out by quad (2倍)
function easeOutQuad(t) {
return t*(2-t)
}
easing out by cubic (3倍)
function easeOutCubic(t) {
return (--t)*t*t+1
}
easing out by quart (4倍)
function easeOutQuart(t) {
return t*t*t*t
}
easing out by quint (5倍)
function easeOutQuint(t) {
return 1+(--t)*t*t*t*t
}
easing in類(開始慢,結束快)
easing in by pow (指數)
function easeInPow(t, d){
return Math.pow((t/d), 5);
}
easing in by quad (2倍)
function easeInQuad(t) {
return t*t
}
easing in by cubic (3倍)
function easeInCubic(t){
return t*t*t
}
easing in by quart (4倍)
function easeInQuart(t) {
return t*t*t*t
}
easing in by quint (5倍)
function easeInQuint(t) {
return t*t*t*t*t
}
ease in and out類(開始慢,中間快,結束慢)
easing in by pow (指數)
function easeInOutPow(t, d){
return t<.5 ? Math.pow((t/d)*1.8, 6.5) : 1 - Math.pow((1-(t/d))*1.8, 6.5);
}
easing in by quad (2倍)
function easeInOutQuad(t) {
return t<.5 ? 2*t*t : -1+(4-2*t)*t
}
easing in by cubic (3倍)
function easeInOutCubic(t) {
return t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1
}
easing in by quart (4倍)
function easeInOutQuart(t) {
return t<.5 ? 8*t*t*t*t : 1-8*(--t)*t*t*t
}
easing in by quint (5倍)
function easeInOutQuint(t) {
return t<.5 ? 16*t*t*t*t*t : 1+16*(--t)*t*t*t*t
}
參考資料
https://gist.github.com/gre/1650294