javascript - 如何将 Jquery.animate 翻译成 Vanilla JS
问题描述
我只使用了 Jquery 代码的一小部分,我想翻译它
$("html,body").animate(
{
scrollTop: sections[counter].offsetTop,
behavior: "smooth",
},
800
);
Window.scrollTo()
不工作
完整代码
let delay = false;
let counter = 0;
// let scrollHeight = 0;
const sections = document.querySelectorAll(".scrolling-block");
function scrollToSection(e, directionY, directionX) {
if (delay) return;
// console.log(e);
delay = true;
if (directionY !== 0) {
// if scroll by y
setTimeout(function () {
delay = false;
}, 1500);
} else {
// if scroll by x
delay = false;
}
if (directionY !== 0 || directionY !== -0) {
e.preventDefault();
}
if (directionY > 0) {
//scroll down
if (counter + 1 !== sections.length) {
// scrollHeight += sections[counter].clientHeight;
counter++;
} else {
scrollHeight = scrollHeight;
counter = counter;
}
$("html,body").animate(
{
scrollTop: sections[counter].offsetTop,
behavior: "smooth",
},
800
);
// console.log(scrollHeight + "\n", counter);
return counter;
} else if (directionY < 0) {
//scroll up
if (counter - 1 !== -1) {
// scrollHeight -= sections[counter - 1].clientHeight;
counter--;
} else {
scrollHeight = scrollHeight;
counter = counter;
}
$("html,body").animate(
{
scrollTop: sections[counter].offsetTop,
behavior: "smooth",
},
800
);
// console.log(scrollHeight);
return counter;
}
}
window.addEventListener(
"wheel",
function (e) {
let directionY = e.deltaY;
let directionX = e.deltaX;
let maxY = sections[sections.length - 1].offsetTop;
if (pageYOffset < maxY - 10) {
// console.log(scrollHeight, " < ", maxY);
if (directionY !== 0) {
e.preventDefault();
}
scrollToSection(e, directionY, directionX);
} else {
if (pageYOffset < maxY && directionY < 0) {
if (directionY !== 0) {
e.preventDefault();
}
scrollToSection(e, directionY, directionX);
}
// console.log(scrollHeight, " > ", maxY);
}
// e.stopPropagation();
},
{ passive: false }
);
解决方案
从技术上讲,scroll 和 scrollTo 都应该做同样的事情
window.scrollTo({
top: 100,
left: 100,
behavior: 'smooth'
});
或者
window.scroll({
top: 100,
left: 100,
behavior: 'smooth'
});
请在此处查看文档:
[1]:https ://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo
[2]:https ://developer.mozilla.org/en-US /docs/Web/API/窗口/滚动
推荐阅读
- matlab - 如何对矩阵进行加权随机抽样 - MatLab
- apache-spark - 非分区非事务配置单元表的自我覆盖是否适用于火花?
- javascript - 如何根据登录用户呈现视图?
- xml - 当前元素文本中双大写文本的 XPath 不是子元素
- wordpress - 单击照片时如何隐藏描述区域并使其显示?
- python - 使用 sharepy 将文件上传到 Sharepoint
- c# - 如何将.net core webapi中的整个请求添加到serilog文件
- python - 特定的导出 pandas 数据框
- matlab - 如何使用 ode45 在 MATLAB 中绘制霍曼转移轨道?
- css - Symfony 5:Css、js 和引导程序(使用 webpack encore 安装)在部署的主机服务器(使用 apache)上不起作用