傳統的錨點定位會與vue-router中的路由設定存在沖突,都是使用'#'進行的,是以這裡使用一直方法來模拟錨點跳轉,并使用tween.js達到動态的過度效果
不使用原生錨點,使用這種方式解決
import '../static/js/animation.js'
import '../static/js/tween.js'
<a href="javascript:;" @click="anchor(dom)" class="title">xxxx</a>
methods:{
anchor:function(e){
let id='anchor-'+e;
let anchor=document.getElementById(id);
let go=anchor.offsetTop;
Math.animation(document.documentElement.scrollTop,go,600,'Quart.easeOut', function (value) {
document.documentElement.scrollTop = value; // animation為封裝的方法
document.body.scrollTop = value; //相容
});
}
}
animation.js
// 對運動方法進行封裝
Math.animation = function (from, to, duration, easing, callback) {
var isUndefined = function (obj) {
return typeof obj == 'undefined';
};
var isFunction = function (obj) {
return typeof obj == 'function';
};
var isNumber = function(obj) {
return typeof obj == 'number';
};
var isString = function(obj) {
return typeof obj == 'string';
};
// 轉換成毫秒
var toMillisecond = function(obj) {
if (isNumber(obj)) {
return obj;
} else if (isString(obj)) {
if (/\d+m?s$/.test(obj)) {
if (/ms/.test(obj)) {
return 1 * obj.replace('ms', '');
}
return 1000 * obj.replace('s', '');
} else if (/^\d+$/.test(obj)) {
return +obj;
}
}
return -1;
};
if (!isNumber(from) || !isNumber(to)) {
if (window.console) {
console.error('from和to兩個參數必須且為數值');
}
return 0;
}
// 緩動算法
var tween = Math.tween || window.Tween;
if (!tween) {
if (window.console) {
console.error('緩動算法函數缺失');
}
return 0;
}
// duration, easing, callback均為可選參數
// 而且順序可以任意
var options = {
duration: 300,
easing: 'Linear',
callback: function() {}
};
var setOptions = function(obj) {
if (isFunction(obj)) {
options.callback = obj;
} else if (toMillisecond(obj) != -1) {
options.duration = toMillisecond(obj);
} else if (isString(obj)) {
options.easing = obj;
}
};
setOptions(duration);
setOptions(easing);
setOptions(callback);
// requestAnimationFrame的相容處理
if (!window.requestAnimationFrame) {
requestAnimationFrame = function (fn) {
setTimeout(fn, 17);
};
}
// 算法需要的幾個變量
var start = 0;
// during根據設定的總時間計算
var during = Math.ceil(options.duration / 17);
// 目前動畫算法
// 確定首字母大寫
options.easing = options.easing.slice(0, 1).toUpperCase() + options.easing.slice(1);
var arrKeyTween = options.easing.split('.');
var fnGetValue;
if (arrKeyTween.length == 1) {
fnGetValue = tween[arrKeyTween[0]];
} else if (arrKeyTween.length == 2) {
fnGetValue = tween[arrKeyTween[0]] && tween[arrKeyTween[0]][arrKeyTween[1]];
}
if (isFunction(fnGetValue) == false) {
console.error('沒有找到名為"'+ options.easing +'"的動畫算法');
return;
}
// 運動
var step = function() {
// 目前的運動位置
var value = fnGetValue(start, from, to - from, during);
// 時間遞增
start++;
// 如果還沒有運動到位,繼續
if (start <= during) {
options.callback(value);
requestAnimationFrame(step);
} else {
// 動畫結束,這裡可以插入回調...
options.callback(to, true);
}
};
// 開始執行動畫
step();
};
最後
大家好,這裡是「 TaoLand 」,這個部落客要用于記錄一個菜鳥程式猿的Growth之路。這也是自己第一次做部落格,希望和大家多多交流,一起成長!文章将會在下列位址同步更新……
個人部落格:
www.yangyuetao.cn 小程式: TaoLand