This article mainly introduces the implementation of a backToTop component in Vue, which can achieve the return to the top effect and has certain reference value. If you are interested, you can learn about
I have been learning VUE recently. I am studying how to use VUE to implement the encapsulation of a component. I will leave a note today
Preface
Back to topThis function can be implemented using jq. It is so easy. Implementation, an animate combined with scrollTo can be done.
Today we will try vue to encapsulate a native js implementation. Return to the top;
It’s quite difficult to write. With the help of github, I looked at other people’s gist and encapsulated it a little. ;
Of course it’s not the kind of direct adjustment using scrollTo. How can it be justified without a transition effect!! It’s still done.
Without further ado, let’s look at the renderings...
Rendering

Implementation ideas
The transition uses requestAnimationFrame, which The product only supports IE10, so it must be compatible
The scroll view is window.pageYOffset, and this product supports IE9;
In order to make it controllable Better, use iconfont for the icon, look at the code in detail
What can you learn?
Learn some pages Calculation related stuff
Some knowledge of animation API
Vue encapsulation component related knowledge and the application of life cycle and event monitoring and destruction related knowledge
Implementation function
-
The view displays the return to top button and icon at 350 by default
Prompt text and color, customization of the top, bottom, left and right of the icon, the fields have limited formats and default values
Icon color, shape, size customization Definition, fields have limited formats and default values
Customization of transition effects, usage: scrollIt(0, 1500, 'easeInOutCubic', callback);
Return to the point of the view, that is, where to scroll
Transition time (ms level)
A bunch of transition effects and string formats are actually rolling calculation functions..
Of course, the default parameters are indispensable, except for callback
The compatibility is IE9, I specially opened the virtual machine to try it
Code
scrollIt.js – Transitional scrolling implementation
export function scrollIt(
destination = 0,
duration = 200,
easing = "linear",
callback
) {
// define timing functions -- 过渡动效
let easings = {
// no easing, no acceleration
linear(t) {
return t;
},
// accelerating from zero velocity
easeInQuad(t) {
return t * t;
},
// decelerating to zero velocity
easeOutQuad(t) {
return t * (2 - t);
},
// acceleration until halfway, then deceleration
easeInOutQuad(t) {
return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
},
// accelerating from zero velocity
easeInCubic(t) {
return t * t * t;
},
// decelerating to zero velocity
easeOutCubic(t) {
return --t * t * t + 1;
},
// acceleration until halfway, then deceleration
easeInOutCubic(t) {
return t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
},
// accelerating from zero velocity
easeInQuart(t) {
return t * t * t * t;
},
// decelerating to zero velocity
easeOutQuart(t) {
return 1 - --t * t * t * t;
},
// acceleration until halfway, then deceleration
easeInOutQuart(t) {
return t < 0.5 ? 8 * t * t * t * t : 1 - 8 * --t * t * t * t;
},
// accelerating from zero velocity
easeInQuint(t) {
return t * t * t * t * t;
},
// decelerating to zero velocity
easeOutQuint(t) {
return 1 + --t * t * t * t * t;
},
// acceleration until halfway, then deceleration
easeInOutQuint(t) {
return t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * --t * t * t * t * t;
}
};
// requestAnimationFrame()的兼容性封装:先判断是否原生支持各种带前缀的
//不行的话就采用延时的方案
(function() {
var lastTime = 0;
var vendors = ["ms", "moz", "webkit", "o"];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame =
window[vendors[x] + "RequestAnimationFrame"];
window.cancelAnimationFrame =
window[vendors[x] + "CancelAnimationFrame"] ||
window[vendors[x] + "CancelRequestAnimationFrame"];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
})();
function checkElement() {
// chrome,safari及一些浏览器对于documentElemnt的计算标准化,reset的作用
document.documentElement.scrollTop += 1;
let elm =
document.documentElement.scrollTop !== 0
? document.documentElement
: document.body;
document.documentElement.scrollTop -= 1;
return elm;
}
let element = checkElement();
let start = element.scrollTop; // 当前滚动距离
let startTime = Date.now(); // 当前时间
function scroll() { // 滚动的实现
let now = Date.now();
let time = Math.min(1, (now - startTime) / duration);
let timeFunction = easings[easing](time);
element.scrollTop = timeFunction * (destination - start) + start;
if (element.scrollTop === destination) {
callback; // 此次执行回调函数
return;
}
window.requestAnimationFrame(scroll);
}
scroll();
}
backToTop.vue
<template>
<p class="back-to-top" @click="backToTop" v-show="showReturnToTop" @mouseenter="show" @mouseleave="hide">
<i :class="[bttOption.iClass]" :style="{color:bttOption.iColor,'font-size':bttOption.iFontsize}"></i>
<span class="tips" :class="[bttOption.iPos]" :style="{color:bttOption.textColor}" v-show="showTooltips">{{bttOption.text}}</span>
</p>
</template>
<script>
import { scrollIt } from './scrollIt'; // 引入动画过渡的实现
export default {
name: 'back-to-top',
props: {
text: { // 文本提示
type: String,
default: '返回顶部'
},
textColor: { // 文本颜色
type: String,
default: '#f00'
},
iPos: { // 文本位置
type: String,
default: 'right'
},
iClass: { // 图标形状
type: String,
default: 'fzicon fz-ad-fanhuidingbu1'
},
iColor: { // 图标颜色
type: String,
default: '#f00'
},
iFontsize: { // 图标大小
type: String,
default: '32px'
},
pageY: { // 默认在哪个视图显示返回按钮
type: Number,
default: 400
},
transitionName: { // 过渡动画名称
type: String,
default: 'linear'
}
},
data: function () {
return {
showTooltips: false,
showReturnToTop: false
}
},
computed: {
bttOption () {
return {
text: this.text,
textColor: this.textColor,
iPos: this.iPos,
iClass: this.iClass,
iColor: this.iColor,
iFontsize: this.iFontsize
}
}
},
methods: {
show () { // 显示隐藏提示文字
return this.showTooltips = true;
},
hide () {
return this.showTooltips = false;
},
currentPageYOffset () {
// 判断滚动区域大于多少的时候显示返回顶部的按钮
window.pageYOffset > this.pageY ? this.showReturnToTop = true : this.showReturnToTop = false;
},
backToTop () {
scrollIt(0, 1500, this.transitionName, this.currentPageYOffset);
}
},
created () {
window.addEventListener('scroll', this.currentPageYOffset);
},
beforeDestroy () {
window.removeEventListener('scroll', this.currentPageYOffset)
}
}
</script>
<style scoped lang="scss">
.back-to-top {
position: fixed;
bottom: 5%;
right: 100px;
z-index: 9999;
cursor: pointer;
width: auto;
i {
font-size: 32px;
display: inline-block;
position: relative;
text-align: center;
padding: 5px;
background-color: rgba(234, 231, 231, 0.52);
border-radius: 5px;
transition: all 0.3s linear;
&:hover {
border-radius: 50%;
background: #222;
color: #fff !important;
}
}
.tips {
display: inline-block;
position: absolute;
word-break: normal;
white-space: nowrap;
width: auto;
font-size: 12px;
color: #fff;
z-index: -1;
}
.left {
right: 0;
top: 50%;
margin-right: 50px;
transform: translateY(-50%);
}
.right {
left: 0;
top: 50%;
margin-left: 50px;
transform: translateY(-50%);
}
.bottom {
bottom: 0;
margin-top: 50px;
}
.top {
top: 0;
margin-bottom: 50px;
}
}
</style>
Summary
From whim to tossing, in order to balance compatibility and expansion Sex, it seemed like a few hours.
But it was realized. If you move to other languages, like ng4, it only takes about ten minutes,
The ideas will be Well, the implementation is more about writing. As for performance optimization, you can think about it while writing, or you can optimize it when you have time after implementation.
The above is the entire content of this article. I hope it will be helpful to everyone's study. , please pay attention to the PHP Chinese website for more related content!
Related recommendations:
About the use of the VUE-region selector (V-Distpicker) component
About vue Introduction to the construction, packaging and release process of the project
The above is the detailed content of Vue implements the component that returns the top backToTop. For more information, please follow other related articles on the PHP Chinese website!
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base
JavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 English version
Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment






