需求:
button悬浮固定在页面底部,
情况1:点击 button时滚动到指定位置, button消失,
情况2:页面手动动到制定位置时,button消失
当滚动区域超出 ,button在显示
代码:
<div :id="'enrll'" ></div>
<van-button v-show="show" @click.prevent="jumpEnrll('#enrll')"/>
data(){
return {
enrllBtnOffsetTop: '',
enrllBtnoffsetHeight: ‘’
}
},
watch:{ //因为是一个文章详情的页面,所以要在dom渲染完成之后获取offsetTop, 这里用watch结合 this.$nextTick()
details(val){
let that = this
this.$nextTick(function(){
let anchor = that.$el.querySelector('#enrll')
that.enrllBtnOffsetTop = anchor.offsetTop //目标dom滚动条位置
that.enrllBtnoffsetHeight = anchor.offsetHeight //dom高度
})
}
},
mounted(){
this.init()
},
methods:{
init(){
axios(//发送请求获取的数据去渲染)
window.addEventListener('scroll',this.handleScroll,true)//监听滚动条
},
handleScroll(e){
let scrollTop = e.target.scrollingElement.scrollTop
let clientHeight = e.target.scrollingElement.clientHeight //可见区域宽度
let scrollHeight = e.target.scrollingElement.scrollHeight //全文高度
let scrollBottomHeight = scrollHeight- this.enrllBtnoffsetHeight - clientHeight //作为滚动条上滑时候显示的基准
if (scrollTop >= this.enrllBtnOffsetTop) {
this.show = false
}
if (scrollTop < scrollBottomHeight) { //滚动条的位置小于基准值的时候 再次显示
this.show = true
}
},
jumpEnrll(form){
// let anchor = this.$el.querySelector(form)
// window.scrollTo({ //最初用的这个方法,但是在手机上不生效
// top: anchor.offsetTop,
// behavior: "smooth"
// });
//this.$el.querySelector(form).scrollIntoView({behavior:'smooth',block:"start"}) //最后手机上这样用(但是在移动端不能平滑滚动,直接跳到锚点位置,效果很差)
// 最后使用这种方式实现平滑滚动
// 平滑滚动,时长500ms,每10ms一跳,共50跳
let anchor = this.$el.querySelector(form)
// 获取当前滚动条与窗体顶部的距离
let scrollTop = document.body.scrollTop
let total = anchor.offsetTop
let step = total/50;
(function smoothDown(){
if (scrollTop < total) {
scrollTop += step
document.body.scrollTop = scrollTop // 每次移动的距离
document.documentElement.scrollTop = scrollTop //兼容
setTimeout(smoothDown, 10) //跳动时间间隔
} else{
document.body.scrollTop = total // 停止滚动的距离
document.documentElement.scrollTop = scrollTop //兼容
}
})()
}
平滑滚动参考代码
网友评论