javascript - Jquery动画没有正确检测滚动
问题描述
我正在尝试制作一个功能,其中一个按钮向上滑动以在滚动后将您带回顶部。但是由于某种原因,它只是行不通。我使用时效果很好
if (scroll >= 84) {
$("#ID").fadeIn();
} else {
$("#ID").fadeOut();
}
但是当它不适用于动画或css时。我跟踪滚动的方式是使用事件监听器,并用值声明一个 let:
let scroll = this.scrollY;
我希望这是足够的信息,可以让您了解我的目标。我在这里先向您的帮助表示感谢
解决方案
试试这个(运行并向下滚动):
var timeout;
for (var i = 0; i < 200; i++) {
document.body.innerHTML += "Example Text<br>"
}
window.addEventListener("scroll", () => {
var scrollDistance = window.scrollY
if (scrollDistance >= 100) {
clearTimeout(timeout);
document.querySelector("button").style.display = "";
setTimeout(function() {
document.querySelector("button").style.opacity = "1"
}, 1);
document.querySelector("button").style.cursor = "pointer";
} else {
clearTimeout(timeout);
document.querySelector("button").style.opacity = "0";
document.querySelector("button").style.cursor = "";
timeout = setTimeout(function() {
document.querySelector("button").style.display = "none"
}, 500);
}
})
document.querySelector("button").addEventListener("click", () => {
window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
});
})
button {
position: fixed;
right: 10px;
bottom: 10px;
border-radius: 50%;
height: 50px;
width: 50px;
display: flex;
justify-content: center;
align-items: center;
background-color: #ffcccb;
border: 2px solid black;
opacity: 0;
outline: none;
transition: opacity 0.5s;
}
button>div {
width: 20px;
height: 20px;
border-width: 5px 5px 0px 0px;
border-style: solid;
border-color: black;
transform: translate(0, 4px) rotate(-45deg);
}
<button>
<div></div>
</button>
请注意,大部分代码只是设置。这是执行滚动工作的实际代码:
document.querySelector("button").addEventListener("click", () => {
window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
});
})
它只是监听按钮的点击,然后滚动到顶部。
推荐阅读
- java - 在 Android、iOS 和 Java (SPRING) 服务器上支持 RSA 加密
- javascript - 如何使用javascript从新日期动态获取最近三个月的开始日期
- php - Laravel 5.8 部署共享主机 500 服务器错误
- rabbitmq - 类似于消息队列的软件,可以重新排序事件
- spotify - Spotify API 调用使用 springTemplate 返回内部服务器错误
- git - GIT 仅合并一系列提交
- c++ - 在数组中倒数。[-1]
- gitlab - 将成员添加到自托管 Gitlab 帐户不起作用
- javascript - 如何滚动定义了最大高度的底部容器?
- javascript - 三元运算符和赋值:不调用同一个函数两次的更好方法