gpt4 book ai didi

javascript - 单击时在 div 处切换 z-index

转载 作者:行者123 更新时间:2023-11-28 17:10:44 25 4
gpt4 key购买 nike

我正在尝试遍历绝对定位并具有 z 索引的子级 div。单击按钮时,我希望 z-index 增加,因此它几乎像一个循环一样工作。所以在每次点击时,我希望当前可见的 div 具有较低的 z 索引,因此一次只有一个 div 可见。

$(function() {
$('button').click(function(){
//.three sholed take the place of .one and .two should jump up one step. i want this to be repeatable.
});
});
body {
margin:0;
padding:0;
}
.holder {
width: 100px;
height:100px;
border:1px solid #000000;
}

.holder div {
width: 100px;
height: 100px;
position:absolute;
top:0;
left:0;
}

.one {
background:red;
z-index:1;
}
.two {
background:green;
z-index:2;
}
.three {
background: blue;
z-index:3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="holder">
<div class="one">1</div>
<div class="two">2</div>
<div class="three">3</div>
</div>
<button>click</button>

最佳答案

使用 jquery 将一个类添加到应具有所需索引/在单击时可见的元素

$("button").click(function(){
$(".current").removeClass("current").next().addClass("current")
});
body {
margin:0;
padding:0;
}
.holder {
width: 100px;
height:100px;
border:1px solid #000000;
}

.holder div {
width: 100px;
height: 100px;
position:absolute;
top:0;
left:0;
z-index:0; /*init z-index*/
}
.holder div.current{z-index:1;} /*only this DIV will be visible*/
.one {
background:red;
}
.two {
background:green;
}
.three {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="holder">
<div class="one current">1</div>
<div class="two">2</div>
<div class="three">3</div>
</div>
<button>click</button>

如果要循环播放

$("button").click(function(){
if($(".holder >div:last-child").hasClass("current")){
$(".holder >div:last-child").removeClass("current");
$(".holder >div:first-child").addClass("current");
}else{
$(".current").removeClass("current").next().addClass("current");
}
});
body {
margin:0;
padding:0;
}
.holder {
width: 100px;
height:100px;
border:1px solid #000000;
}

.holder div {
width: 100px;
height: 100px;
position:absolute;
top:0;
left:0;
z-index:0; /*init z-index*/
}
.holder div.current{z-index:1;} /*only this DIV will be visible*/
.one {
background:red;
}
.two {
background:green;
}
.three {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="holder">
<div class="one current">1</div>
<div class="two">2</div>
<div class="three">3</div>
</div>
<button>click</button>

关于javascript - 单击时在 div 处切换 z-index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29283025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com