我想在5秒的时间间隔内一个接一个地渲染这些div。当第二个渲染第一个div时,需要隐藏第一个div,这需要是一个循环过程。我尝试了一些设置的间隔,但无法实现。请帮我实现这一点。
当前行为:
它可以像这个一样直接打印
<div id="popup-wrap">
<div id="1" class='popup-wrap'>div one</div>
<div id="2" class='popup-wrap'>div two</div>
</div>
请在下面找到我的代码:
const myObject = {
"1": {
"eventJson": "<div>div one</div>"
},
"2": {
"eventJson": "<div>Div two</div>"
}
}
};
Object.keys(myObject).map(function (key, index) {
getRenderhtml(myObject[key], key);
});
const getRenderhtml = (jsonHtml, key) => {
var popup = document.createElement("div");
popup.setAttribute("id", key);
popup.setAttribute("class", "Popup");
const html = jsonHtml.eventJson;
popup.innerHTML = html;
document.getElementById("popup-wrap").appendChild(popup);
const element = document.getElementById(key);
element.style.visibility = "none";
element.style.opacity = "1";
element.style.display = "block";
element.style.position = "fixed";
// element.style.top = "0px";
element.style.left = "10px";
// element.style.right = "0px";
element.style.bottom = "10px";
};
提前感谢
这里有一种方法。使用setInterval循环,找到当前显示的div,隐藏它,然后移动到下一个,当我们到达末尾时重置为零。此示例设置为每秒循环一次,用于演示
const myObject = {
"1": {
"eventJson": "<div>div one</div>"
},
"2": {
"eventJson": "<div>Div two</div>"
}
}
// write the objects to the dom
document.querySelector('#popup-wrap').innerHTML = Object.entries(myObject)
.map(e => e[1].eventJson.replace("<div>", `<div class='popup-wrap hidden' id='${e[0]}'>`))
.join('');
// set up the rotate function
const rotateItem = () => {
let currentIndex = -1,
p = document.querySelectorAll('.popup-wrap')
p.forEach((e, i) => {
if (!e.classList.contains('hidden')) {
currentIndex = i + 1;
e.classList.add('hidden')
}
});
currentIndex = Math.max(currentIndex, 0);
if (currentIndex >= p.length) currentIndex = 0;
p[currentIndex].classList.remove('hidden')
}
const interv = setInterval(rotateItem, 1000)
.popup-wrap {
padding: 15px;
background: #f0f0f0;
}
.popup-wrap.hidden {
display: none;
}
<div id="popup-wrap"></div>