fix(Sticky): avoid sticky not fixed when scroll slow & improve performance (#2703)

fix #2310
This commit is contained in:
rex 2020-01-20 20:31:03 +08:00 committed by GitHub
parent 33c11facff
commit 5ed7ed5e1d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 31 additions and 28 deletions

View File

@ -35,27 +35,11 @@ VantComponent({
},
data: {
wrapStyle: '',
containerStyle: ''
height: 0,
fixed: false
},
methods: {
setStyle() {
const { offsetTop, height, fixed, zIndex } = this.data;
if (fixed) {
this.setData({
wrapStyle: `top: ${offsetTop}px;`,
containerStyle: `height: ${height}px; z-index: ${zIndex};`
});
} else {
this.setData({
wrapStyle: '',
containerStyle: ''
});
}
},
getContainerRect() {
const nodesRef: WechatMiniprogram.NodesRef = this.data.container();
@ -96,9 +80,8 @@ VantComponent({
this.disconnectObserver('contentObserver');
const contentObserver = this.createIntersectionObserver({
thresholds: [0, 1]
thresholds: [0.9, 1]
});
this.contentObserver = contentObserver;
contentObserver.relativeToViewport({ top: -offsetTop });
contentObserver.observe(ROOT_ELEMENT, res => {
if (this.data.disabled) {
@ -107,6 +90,8 @@ VantComponent({
this.setFixed(res.boundingClientRect.top);
});
this.contentObserver = contentObserver;
},
observeContainer() {
@ -122,7 +107,7 @@ VantComponent({
this.disconnectObserver('containerObserver');
const containerObserver = this.createIntersectionObserver({
thresholds: [0, 1]
thresholds: [0.9, 1]
});
this.containerObserver = containerObserver;
containerObserver.relativeToViewport({
@ -145,7 +130,7 @@ VantComponent({
const fixed =
containerHeight && height
? top > height - containerHeight && top < offsetTop
? top >= height - containerHeight && top < offsetTop
: top < offsetTop;
this.$emit('scroll', {
@ -154,10 +139,6 @@ VantComponent({
});
this.setData({ fixed });
wx.nextTick(() => {
this.setStyle();
});
}
},

View File

@ -1,7 +1,8 @@
<wxs src="../wxs/utils.wxs" module="utils" />
<wxs src="./index.wxs" module="computed" />
<view class="custom-class van-sticky" style="{{ containerStyle }}">
<view class="{{ utils.bem('sticky-wrap', { fixed }) }}" style="{{ wrapStyle }}">
<view class="custom-class van-sticky" style="{{ computed.containerStyle({ fixed, height, zIndex }) }}">
<view class="{{ utils.bem('sticky-wrap', { fixed }) }}" style="{{ computed.wrapStyle({ fixed, offsetTop }) }}">
<slot />
</view>
</view>

21
packages/sticky/index.wxs Normal file
View File

@ -0,0 +1,21 @@
/* eslint-disable */
function wrapStyle(data) {
if (data.fixed) {
return 'top: ' + data.offsetTop + 'px;';
}
return '';
}
function containerStyle(data) {
if (data.fixed) {
return 'height: ' + data.height + 'px; z-index: ' + data.zIndex + ';';
}
return '';
}
module.exports = {
wrapStyle: wrapStyle,
containerStyle: containerStyle
};