vue 中实现回到顶部的两种方式:

(1)锚点方式

通过点击锚点回到指定位置:

<template>
<div id="topAnchor" ref="faultTree" class="wrap">
<a id="TOPUp" href="#topAnchor">
<img style="width: 100%;height: 100%;" src="../../../../assets/top.png" alt="">
</a>
<!--其他业务逻辑代码-->
...
</div>
</template>

样式:

<style>
#TOPUp{
position: fixed;
right: 45px;
bottom: 100px;
width: 40px;
height: 40px;
z-index: 99999999;
box-shadow: 0px 0px 4px 4px #ecefef;
border-radius: 600px;
}
</style>

实现效果:

vue项目实现回到顶部的两种超简单方法_echarts(2)scrollTop

通过点击事件将scrollTop重置为0,从而达到返回顶部的效果。

<template>
<div class="hello_world">
<button class="top" @click="toTop">^</button>
</div>
</template>

<script>
export default {
methods: {
toTop() {
document.documentElement.scrollTop = 0;
},
},
};
</script>

<style>
.hello_world {
height: 5000px;
}
.top {
position: fixed;
width: 30px;
height: 30px;
bottom: 50px;
right: 100px;
background-color: aqua;
}
</style>

代码资源链接

​代码地址​