官网示例:
<el-backtop target=".page-component__scroll .el-scrollbar__wrap" :bottom="100">
<div
>
UP
</div>
</el-backtop>
注意:target属性是为了获取产生滚动条的dom元素,所以target属性里面的类,应该要精准指向产生滚动条的dom对象,要不然就无法生效,参考el-backtop组件源码:
<template>
<transition name="el-fade-in">
<div
v-if="visible"
@click.stop="handleClick"
:style="{
'right': styleRight,
'bottom': styleBottom
}"
class="el-backtop">
<slot>
<el-icon name="caret-top"></el-icon>
</slot>
</div>
</transition>
</template>
<script>
import throttle from 'throttle-debounce/throttle';
export default {
name: 'ElBacktop',
props: {
visibilityHeight: {
type: Number,
default: 200
},
target: [String],
right: {
type: Number,
default: 40
},
bottom: {
type: Number,
default: 40
}
},
data() {
return {
el: null,
container: null,
visible: false
};
},
computed: {
styleBottom() {
return `${this.bottom}px`;
},
styleRight() {
return `${this.right}px`;
}
},
mounted() {
this.init();
this.throttledScrollHandler = throttle(300, this.onScroll);
this.container.addEventListener('scroll', this.throttledScrollHandler);
},
methods: {
init() {
this.container = document;
this.el = document.documentElement;
if (this.target) {
this.el = document.querySelector(this.target);
if (!this.el) {
throw new Error(`target is not existed: ${this.target}`);
}
this.container = this.el;
}
},
onScroll() {
const scrollTop = this.el.scrollTop;
this.visible = scrollTop >= this.visibilityHeight;
},
handleClick(e) {
this.scrollToTop();
this.$emit('click', e);
},
scrollToTop() {
let el = this.el;
let step = 0;
let interval = setInterval(() => {
if (el.scrollTop <= 0) {
clearInterval(interval);
return;
}
step += 10;
el.scrollTop -= step;
}, 20);
}
},
beforeDestroy() {
this.container.removeEventListener('scroll', this.throttledScrollHandler);
}
};
</script>
根据源码中init()函数可知,当target未设置时,当前滚动操作对象默认为document.documentElement对象,即html根节点,当设置了target时,会根据target里面填写的类名去querySelector查找该元素,而且根据该类应只能精准查找到一个元素,注意querySelector和querySelectorAll的区别,前者只返回对应查找条件找到的第一个元素,所以target类名要精准且唯一,否则backtop组件则无效。