问题描述
我在线上搜索了很多数据,但仍然对DOMcontentLoaded
和window.onload
感到困惑。在代码中,加载窗口时,将显示导航栏和第一页。我可以看到gameTitle和carouselTemplate
渲染的图像。现在,我想使用Intersection Observer API进行无限滚动。因此,在document.addEventListener('DOMContentLoaded',())
中,我尝试获取gameTitle,但控制台显示null
。我不知道为什么在DOM加载后无法获取元素?如果将DOMContentLoaded更改为滚动,则可以获取该元素。我该如何改善这个问题?谢谢!
const baseAPI = 'https://api.url.com/';
const topAPI = `${baseAPI}games/top?limit=5`;
const Api = `${baseAPI}streams/`;
let offset = 0;
function carouselTemplate(gameName,gameNameurl) {
return `
<div class="col-ms-12 col-md-12 pl-0 pr-0 d-flex align-items-center justify-content-center">
<p class="gameTitle">${gameName}</p>
<img class="image" src="https://static-cdn.jtvnw.net/ttv-Boxart/${gameNameurl}-272x380.jpg" alt="First slide">
</div>
`
}
window.onload = function () {
fetchTopgames(topAPI)
.then((data) => {
const topGames = [...data.top];
const gameName = topGames[0].game.name
const defaultGamename = encodeURIComponent(gameName);
let topGamestr = ''
topGames.map(topGame => {
topGamestr += navbarTemplate(topGame.game.name);
})
navList.innerHTML = topGamestr;
carousel.innerHTML = carouselTemplate(gameName,defaultGamename);
// if navbar is created
if (navList) {
const firstChild = navList.firstElementChild.firstElementChild;
firstChild.classList.add('activeColor');
getgames(Api,defaultGamename,offset);
}
})
.catch((error) => {
console.log(error);
})
}
document.addEventListener('DOMContentLoaded',() => {
const gameName = document.querySelector('.gameTitle');
console.log(gameName)
const gameNameurl = encodeURIComponent(gameName);
const options = {
root: document.querySelector('.container-fluid'),threshold: 1
};
const observer = new IntersectionObserver((entry) => {
console.log(entry)
},options)
const target = document.querySelector('.observer');
// let callback = ([entry]) => {
// if (entry && entry.isIntersecting) {
// getgames(Api,gameNameurl,offset);
// offset += 20;
// }
// }
observer.observe(target);
})
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)