[英]How to scroll to an element using Javascript?
单击按钮时,我试图滚动到特定的卡片。 我为此使用了 scrollIntoView,但它不起作用。
.js 文件:
document.getElementById("general_details_edit").addEventListener("click", function(){
this.style.display = "none";
document.getElementById("general_details_card").classList.remove("d-none");
document.getElementById("general_details_card").classList.add("d-block");
console.log("start");
document.getElementById("general_details_card").scrollIntoView({behavior : 'smooth'});
console.log("end")
//not working
所有其他 javascript 代码都在工作。 我该如何解决这个问题? 我也收到控制台消息“开始”和“结束”。
此外,当我从浏览器的控制台运行同一行时,它可以工作。
编辑 :
Vijay 关于使用超时的评论对我有用。 但是我如何等待元素加载而不是等待特定的时间?
当前代码:
const scroll = (el) => {
setTimeout(function () { el.scrollIntoView( {behavior : 'smooth', block : 'end'}); }, 500);
}
一种方法是在 DOM 完全加载后将等待时间更改为零毫秒。
var mSeconds = 500;
window.addEventListener('DOMContentLoaded', function(event) {
mSeconds = 0;
});
const scroll = (el) => {
setTimeout(function () {
el.scrollIntoView( {behavior : 'smooth', block : 'end'});
}, mSeconds);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.