延迟需要生成 DOM 的 JavaScript 进程的最聪明方法是什么?



我必须在html DOM的元素中自动滚动。现在,我需要使用两个setTimeout函数来处理调用此函数的不同方式。所以这段代码解决了我的问题,但我觉得它很丑。

app.ports.scrollingTo.subscribe(function(id){
function scroller(id) {
setTimeout(function() {
var node = document.getElementById(id);
if (node != null) {
setTimeout(function() {
node.scrollIntoView({behavior: "smooth", block: "start"});
}, 10)
}}, 10)}
window.onload = scroller(id);
})

有没有更好的方法来确保在执行延迟代码之前加载 DOM ?

window.onload = function() {
//your code
}

所以你可以使用MutationObserver来做到这一点,前提是你有一个可以在此之前观察的元素。

在此示例中,您可以看到我正在观察父容器,直到节点存在,然后将其滚动到视图中

const container = document.getElementById('container');
function containerChanged( mutationsList, observer ) {
for(let mutation of mutationsList) {
if (mutation.type === 'childList' || mutation.type === 'subtree') {
var node = document.getElementById('element10');
if (node) {
node.scrollIntoView({behavior: "smooth", block: "start"});
observer.disconnect();
}
}
}
};
let count = 0;
let interval = setInterval(function() {
const el = document.createElement('div');
el.id = 'element' + (++count);
el.innerHTML = 'I am element ' + el.id;
container.appendChild( el );
if (count > 15) {
clearInterval( interval );
}
}, 100);
const observer = new MutationObserver(containerChanged);
observer.observe( container, { childList: true, subtree: true });
#container {
height: 120px;
max-height: 120px;
overflow-y: auto;
border: solid #a0a0a0 1px;
}
<div id="container">
</div>

最新更新