基于vue.js 2.x的虚拟滚动条的示例代码(2)
2 事件,主要是当鼠标移动的时候,显示滚动条。
...
render(_c){
return _c(
// ...
{
mouseenter: function(e) {
vm.$emit('showVBar'); // 触发父组件事件,显示滚动条
}
}
// ...
)
}
其中 state 表示状态,是在运行时可发生改变的,而 ops 则是配置参数,是用户传过来的。
scrollPanel
包裹滚动内容的组件,样式需设置为: overflow: hidden 。
1、样式
var style = vm.scrollContentStyle;
style.overflow = 'hidden';
// ...
{
style: style
}
// ...
2、事件
// ...
render(_c) {
// ...
on: {
mouseenter: function() {
vm.$emit('showBar');
},
mouseleave: function() {
vm.$emit('hideBar');
}
}
// ...
}
// ...
vuescroll
控制组件。控制子组件显示的状态,添加各种监听事件等。
1、取得子组件的dom元素,用来取得dom的实时信息。
// ...
initEl() {
this.scrollPanel.el = this.$refs['vueScrollPanel'] && this.$refs['vueScrollPanel'].$el;
this.vScrollBar.el = this.$refs['vScrollBar'] && this.$refs['vScrollBar'].$el;
this.hScrollBar.el = this.$refs['hScrollBar'] && this.$refs['hScrollBar'].$el;
}
// ...
2、显示滚动条
显示滚动条,包括显示水平滚动条和显示垂直滚动条,这里以显示垂直滚动条为例:
// ...
var temp;
var deltaY = {
deltaY: this.vScrollBar.ops.deltaY // 获取用户配置的deltaY
};
if(!this.isMouseLeavePanel || this.vScrollBar.ops.keepShow){
if ((this.vScrollBar.state.height = temp = this.getVBarHeight(deltaY))) { // 判断条件
// 重新设置滚动条的状态
this.vScrollBar.state.top = this.resizeVBarTop(temp);
this.vScrollBar.state.height = temp.height;
this.vScrollBar.state.opacity = this.vScrollBar.ops.opacity;
}
}
// ...
3、获取滚动条的高度
因为dom元素的高度不是固定的,所以你要实时地获取dom真实的高度,滚动条的高度计算公式如下:
var height = Math.max(
scrollPanelHeight /
(scrollPanelScrollHeight / scrollPanelHeight),
this.vScrollBar.minBarHeight
);
即: 滚动条的高度:scrollPanel的高度 == scrollPanel的高度:dom元素高度
4、resizeVBarTop ,为了防止误差,并且可以求出滚动条距离父元素的高度。
resizeVBarTop({height, scrollPanelHeight, scrollPanelScrollHeight, deltaY}) {
// cacl the last height first
var lastHeight = scrollPanelScrollHeight - scrollPanelHeight - this.scrollPanel.el.scrollTop;
if(lastHeight < this.accuracy) {
lastHeight = 0;
}
var time = Math.abs(Math.ceil(lastHeight / deltaY));
var top = scrollPanelHeight - (height + (time * this.vScrollBar.innerDeltaY));
return top;
}
内容版权声明:除非注明,否则皆为本站原创文章。

