2023-04-19 05:20:02 +08:00
|
|
|
import {Component} from './component';
|
2017-08-07 04:08:03 +08:00
|
|
|
|
2022-11-15 07:19:02 +08:00
|
|
|
export class BackToTop extends Component {
|
2017-08-07 04:08:03 +08:00
|
|
|
|
2022-11-15 07:19:02 +08:00
|
|
|
setup() {
|
|
|
|
this.button = this.$el;
|
2017-08-07 04:08:03 +08:00
|
|
|
this.targetElem = document.getElementById('header');
|
|
|
|
this.showing = false;
|
|
|
|
this.breakPoint = 1200;
|
2018-05-20 16:48:11 +08:00
|
|
|
|
|
|
|
if (document.body.classList.contains('flexbox')) {
|
2022-11-15 07:19:02 +08:00
|
|
|
this.button.style.display = 'none';
|
2018-05-20 16:48:11 +08:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-11-15 07:19:02 +08:00
|
|
|
this.button.addEventListener('click', this.scrollToTop.bind(this));
|
2017-08-07 04:08:03 +08:00
|
|
|
window.addEventListener('scroll', this.onPageScroll.bind(this));
|
|
|
|
}
|
|
|
|
|
|
|
|
onPageScroll() {
|
2023-04-19 05:20:02 +08:00
|
|
|
const scrollTopPos = document.documentElement.scrollTop || document.body.scrollTop || 0;
|
2017-08-07 04:08:03 +08:00
|
|
|
if (!this.showing && scrollTopPos > this.breakPoint) {
|
2022-11-15 07:19:02 +08:00
|
|
|
this.button.style.display = 'block';
|
2017-08-07 04:08:03 +08:00
|
|
|
this.showing = true;
|
|
|
|
setTimeout(() => {
|
2022-11-15 07:19:02 +08:00
|
|
|
this.button.style.opacity = 0.4;
|
2017-08-07 04:08:03 +08:00
|
|
|
}, 1);
|
|
|
|
} else if (this.showing && scrollTopPos < this.breakPoint) {
|
2022-11-15 07:19:02 +08:00
|
|
|
this.button.style.opacity = 0;
|
2017-08-07 04:08:03 +08:00
|
|
|
this.showing = false;
|
|
|
|
setTimeout(() => {
|
2022-11-15 07:19:02 +08:00
|
|
|
this.button.style.display = 'none';
|
2017-08-07 04:08:03 +08:00
|
|
|
}, 500);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
scrollToTop() {
|
2023-04-19 05:20:02 +08:00
|
|
|
const targetTop = this.targetElem.getBoundingClientRect().top;
|
|
|
|
const scrollElem = document.documentElement.scrollTop ? document.documentElement : document.body;
|
|
|
|
const duration = 300;
|
|
|
|
const start = Date.now();
|
|
|
|
const scrollStart = this.targetElem.getBoundingClientRect().top;
|
2017-08-07 04:08:03 +08:00
|
|
|
|
|
|
|
function setPos() {
|
2023-04-19 05:20:02 +08:00
|
|
|
const percentComplete = (1 - ((Date.now() - start) / duration));
|
|
|
|
const target = Math.abs(percentComplete * scrollStart);
|
2017-08-07 04:08:03 +08:00
|
|
|
if (percentComplete > 0) {
|
|
|
|
scrollElem.scrollTop = target;
|
|
|
|
requestAnimationFrame(setPos.bind(this));
|
|
|
|
} else {
|
|
|
|
scrollElem.scrollTop = targetTop;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
requestAnimationFrame(setPos.bind(this));
|
|
|
|
}
|
|
|
|
|
2023-04-19 05:20:02 +08:00
|
|
|
}
|