vue使用better-scroll監聽滑動效果
ps: 實現某元素吸頂 或 滑動到某個元素時固定顯示 ,反之隱藏(根據需求)
使用: better-scroll插件
寫的不好,不足之處,歡迎大家指導, 謝謝!
效果圖
- 當滑到 商品介紹 時, 顯示元素,否則隱藏
前提準備
- 安裝: npm i better-scroll -S
- 組件中引入: import BScroll from ‘better-scroll’
- better-scroll官網
- 參考: better-scroll參數和方法
template
<template>
<section class="goodsInfoWrap" v-if="goods.projectName">
<div class="contentList" ref="listWrapperL">
<!-- 滑動的部分, 需用盒子包裹 -->
<div>
<!-- 省略 -->
<!-- 商品介紹 -->
<section class="goodsDetail" id="boxItem" ref="boxItem">
<div class="tip">
<img src="../../assets/images/icon/productDesc.jpg" alt="">
</div>
<div class="goodsContent" v-html="goods.projectDetailed"></div>
</section>
</div>
</div>
<!-- 固定title -->
<section class="topFixed" v-show="isScroll" :class="isScroll == true ? 'isFixed' : ''" @click="toReferrals">
<div class="lefts">獎勵:{{goods.commissionOne}}%</div>
<div class="rights">
<div class="btn">
<div>點擊我吧</div>
</div>
</div>
</section>
</section>
</template>
初始化及使用better-scroll
<script>
import BScroll from 'better-scroll';
export default {
name: 'goodsInfo',
data() {
return {
isScroll: false, //顯示固定元素
scrollY: '',
}
},
mounted() {
//在mounted中初始化 better-scroll
//備註: 這裏使用定時器因數據多,根據個人使用
setTimeout(() => {
this.initScroll();
}, 600)
},
methods: {
destroy() {
this.listScroll.destroy()
},
destroyed() {
this.$refs.listScroll && this.$refs.listScroll.destroy()
},
initScroll() {
this.$nextTick(()=>{
if (!this.$refs.listWrapperL) {
return
}
//配置: 可根據個人需求
this.listScroll = new BScroll(this.$refs.listWrapperL,{
probeType: 3,
scrollY: true,
click: true,
useTransition:false, // 防止iphone微信滑動卡頓
bounce:true,
momentumLimitDistance: 5
});
this.listScroll.on('scroll', (pos) => {
var tops = this.$refs.boxItem.offsetTop;
// 使用abs絕對值(否則 pos.y拿到值是負數)
this.scrollY = Math.abs(Math.round(pos.y));
//判斷滑動距離大於"商品介紹"元素時, 吸頂title,否則隱藏
if(this.scrollY >= tops) {
this.isScroll = true;
}else {
this.isScroll = false;
}
})
});
},
}
}
</script>
樣式scss
.topFixed {
@include wh(100%, 1rem);
position: fixed;
top: 0;
left: 0;
z-index: 2;
background: #fff;
@include fc;
@include fb;
padding: 0 0.29rem 0 0.38rem;
box-shadow: 2.9px 5.2px 8px 0px rgba(109, 109, 109, 0.1);
.lefts {
@include sc(0.36rem, #fe532e);
}
.rights {
.btn {
@include fcc;
height: 0.66rem;
>div {
height: 100%;
@include sc(0.3rem, #fff);
@include fc;
padding: 0 0.3rem;
background: $bc;
@include borderRadius(0.35rem);
}
}
}
}
//注意: 最外層樣式寬高設置100%及定位
.contentList {
position: absolute;
width: 100%;
height: 100%;
top: 0px;
left: 0;
right: 0;
bottom: 0;
overflow: hidden;
-webkit-overflow-scrolling: touch;
}
.isFixed {
position: fixed;
background-color: #fff;
top: 0;
z-index: 999;
transition: all 0.5s;
}