在计时器上交换div

问题描述 投票:0回答:3

我有2个DIV是绝对定位的同一个地方。我想显示一个10秒,然后隐藏它并显示另一个,依此类推。但不太确定如何去做。谢谢

<div id="div1"></div>
<div id="div2"></div>


#div1 {
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 100px;
background: red;
}

#div2 {
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 100px;
background: blue;
display: none;
}
javascript css
3个回答
0
投票

尝试这样的事情:

<script>
$(document).ready(function(){
    setInterval(ToggleDiv, 10000);
});
function ToggleDiv(){
    $(#div1).toggle();
    $(#div2).toggle();
}
</script>

0
投票

这是使用的javascript,因此您不必为几行代码下载整个Javascript库。只需将它放在你的</body>标签之前。

var d1 = document.getElementById('div1'), d2 = document.getElementById('div2');
function toggle(){
    var showDiv1 = d1.style.display === 'none';
    d1.style.display = showDiv1 ? 'block' : 'none';
    d2.style.display = showDiv1 ? 'none' : 'block';
}
setInterval(toggle, 10000);

0
投票

你可以使用CSS动画

#div1 {
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 100px;
background: red;
z-index:2;
animation: A 20s linear infinite;
}
#div2 {
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 100px;
background: blue;
z-index:1;
animation: B 20s linear infinite;
}
@keyframes A{50%{z-index:1;}}
@keyframes B{50%{z-index:2;}}
<div id="div1"></div>
<div id="div2"></div>
© www.soinside.com 2019 - 2024. All rights reserved.