Плавное появление и исчезновение блока при прокрутке на чистом javascript
window.addEventListener('DOMContentLoaded', function() {
const scrollUpButton = document.querySelector('.backToTop');
if (scrollUpButton) {
scrollUpButton.addEventListener('click', function name() {
window.scrollTo({
top: 0,
behavior: 'smooth',
});
});
window.addEventListener('scroll', function() {
const scrolled = window.pageYOffset || document.documentElement.scrollTop;
if (scrolled >= 800) {
scrollUpButton.classList.add('backToTop_visible');
} else {
scrollUpButton.classList.remove('backToTop_visible');
}
});
}
});
.backToTop {
display: none;
position: fixed;
width: 45px;
height: 45px;
background-color: #000;
line-height: 45px;
text-align: center;
color: #fff;
top: auto;
left: auto;
right: 60px;
bottom: 120px;
cursor: pointer;
border-radius: 2px;
transition: opacity .3s ease-in;
opacity: 0.6;
}
.backToTop::before {
display: inline-block;
position: relative;
vertical-align: middle;
content: '';
background-image: url("../img/sprites/svgSprites.svg#backToTop");
background-repeat: no-repeat;
background-size: 20px 20px;
width: 20px;
height: 20px;
}
.backToTop:hover {
opacity: 1;
}
.backToTop_visible {
display: block;
}
<div class="backToTop page__backToTop icon_backToTop"></div>
Ответы (1 шт):
Автор решения: MaximLensky
→ Ссылка
Может быть так ?
Смотреть на весь экран
let body = document.querySelector("body");
let bHeight = body.getBoundingClientRect().height;
let screenY = window.innerHeight / 2;
let btn = document.querySelector("#btn");
window.onscroll = function() {
if (pageYOffset > screenY) {
btn.classList.add("fixed");
} else {
btn.classList.remove("fixed");
}
}
btn.onclick = function() {
window.scrollTo({
top: 0,
behavior: 'smooth',
});
}
body {
margin: 0;
}
section {
height: 100vh;
}
section:nth-child(1) {
background: red;
}
section:nth-child(2) {
background: green;
}
section:nth-child(3) {
background: blue;
}
section:nth-child(4) {
background: pink;
}
section:nth-child(5) {
background: yellow;
}
#btn {
position: fixed;
bottom: 30px;
right: 30px;
transform: scale(0);
transition: 0.34s linear;
}
#btn.fixed {
transform: scale(1);
}
<section></section>
<section></section>
<section></section>
<section></section>
<section></section>
<button id="btn">Вверх</button>