在游览各类官网时,经常会看到他们的官网在屏幕上下滚动时有一个缓冲效果,效果就是下图这样(图片来源:パティスリー GIN NO MORI,吐槽一下日本的平面设计水平是真的高)
使用
- 恰好最近的工作中需要用到这个,我就写了一个,需要的话可以直接npm下载使用:
npm install vue-scroll-buffer
- 然后再app.vue中引入vue-scroll-buffer,并调用。
<script>
import BufferAnimation from 'vue-scroll-buffer'
export default {
mounted() {
BufferAnimation(10)
}
};
</script>
配置项
- 调用函数时传参来改变缓冲动画的持续时长,可选值为1~20,值越小的话,动画时间越长,默认值为10。
BufferAnimation(10)
预览
-
效果对比图如下,左边是游览器的默认滚动效果,右边是添加了动画的效果。
预览图
源码如下
;(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.NProgress = factory();
}
})(this, function() {
var BufferAnimation = function(wrapperSpeed) {
let o = wrapperSpeed;
o < 1 ? (o = 1) : o > 20 ? (o = 20) : (o = o);
var setting = {
wrapper: "#app",
wrapperSpeed: o / 100
},
i =
window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
window.requestAnimationFrame = i;
var s = window.cancelAnimationFrame || window.mozCancelAnimationFrame,
t = function() {
this.wrapper = "";
this.windowHeight = 0;
this.wapperOffset = 0;
};
t.prototype = {
isAnimate: false,
isResize: false,
scrollId: "",
resizeId: "",
init: function(t) {
this.wrapper = "";
this.windowHeight = 0;
this.wapperOffset = 0;
this.wrapper = document.querySelector(setting.wrapper);
console.log(this.wrapper)
document.body.style.height = this.wrapper.clientHeight + "px";
this.windowHeight = window.clientHeight;
this.attachEvent();
this.wrapperInit();
this.animate();
this.resize();
},
wrapperInit: function() {
this.wrapper.style.width = "100%";
this.wrapper.style.position = "fixed";
},
scroll: function() {
(this.scrollTop =
document.documentElement.scrollTop || document.body.scrollTop),
this.wrapperUpdate(this.scrollTop);
},
animate: function() {
this.scroll();
this.scrollId = i(this.animate.bind(this));
},
wrapperUpdate: function() {
this.wapperOffset +=
(this.scrollTop - this.wapperOffset) * setting.wrapperSpeed;
this.wrapper.style.transform =
"translate3d(0," +
Math.round(100 * -this.wapperOffset) / 100 +
"px ,0)";
},
resize: function() {
var t = this;
t.windowHeight =
window.innerHeight || document.documentElement.clientHeight || 0;
t.resizeId = i(t.resize.bind(t));
},
attachEvent: function() {
var t = this;
window.addEventListener("resize", function() {
t.isResize ||
(s(t.resizeId),
s(t.scrollId),
(t.isResize = !0),
setTimeout(function() {
t.isResize = false;
t.resizeId = i(t.resize.bind(t));
t.scrollId = i(t.animate.bind(t));
}, 200));
});
}
};
new t();
t.prototype.init();
}
return BufferAnimation
})
网友评论