如何使用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代码都在工作。我该如何解决这个问题?我得到控制台消息"start"one_answers";以何种;。

同样,当我从浏览器的控制台中运行同一行时,它可以工作。

编辑:

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);

}

相关内容

最新更新