gpt4 book ai didi

javascript - 添加和删​​除类不同的元素

转载 作者:可可西里 更新时间:2023-11-01 13:30:49 24 4
gpt4 key购买 nike

所以我目前正在学习 jquery 和一些用于动画的 tweenlite(我想保持基础)。所以我目前正在构建一个投资组合网格,但我想添加一个元素的点击,另一个元素正在淡入(从右边滑动没关系)。

但是我无法找到一种方法来使 1 个元素有 1 个要显示的框而另一个元素有一个不同的框要显示而无需一遍又一遍地处理代码并且每次都更改一个简单的数字,必须有一种无需一遍又一遍地重复代码即可使其工作的方法。

我创建了一个代码笔来展示我的挣扎所在。

我希望我对这个问题的描述很清楚:)

HTML

  <div class="box">
<div class="show">Show 1</div>
</div>

<div class="bigbox">
<div class="removeit">
<div class="bigshow">Bigshow 1</div>
</div>
</div>

<div class="box">
<div class="show">Show 2</div>
</div>

<div class="bigbox">
<div class="removeit">
<div class="bigshow">Bigshow 2</div>
</div>
</div>

</div>

CSS

.container {
overflow: auto;
margin: 0 auto;
width:500px;
}

.box {
height:200px;
width:200px;
background:yellow;
text-align:center;
cursor:pointer;
margin:0 auto;
float:left;
margin-right:50px;
}

.bigbox {
height:100%;
width:100%;
background-color: grey;
z-index:100;
left:0;
opacity: 0;
position: fixed;
display:none;
top:0;
.removeit {
height:100px;
width: 100px;
top: 0;
right:0;
background-color: blue;
margin:0 auto;
cursor:pointer;
}
}

.show {
display:block;
}
.noscroll {
overflow:hidden;
}

Javascript

$(".box").click(function(){
$(".bigbox").addClass("show");
TweenLite.to($('.bigbox'), 0.5, {
opacity:1,
autoAlpha:1
});
});

$(".removeit").click(function(){
TweenLite.to($('.bigbox'), 0.5, {
autoAlpha:0,
opacity:0
});
});

代码笔

http://codepen.io/denniswegereef/pen/MwjOXP

最佳答案

正如我在评论中提到的,如果我们不修改 HTML,我认为可以找到 boxbigbox 之间的共同点。这个共同点应该是它们各自类别的 index 值。

  • 所以首先在点击处理程序中存储一个clickedIndex变量像这样:var clickedIndex=$('.box').index($(this));.
  • 然后输入此 clickedIndex 以获得选择性 bigbox,如下所示:var
    bigbox=$(".bigbox").eq(clickedIndex);
    .
  • 最后,使用这个 bigbox 变量进一步淡入或淡出。

这是您修改后的 JavaScript:

var bigbox = null;
var clickedIndex = -1;
var boxElements=$(".box");
var bigboxElements=$(".bigbox");
var removeItElements=$(".removeit");
boxElements.click(function() {
clickedIndex = boxElements.index($(this));
bigbox = bigboxElements.eq(clickedIndex);
bigbox.addClass("show");
TweenLite.to(bigbox, 0.5, {opacity: 1,autoAlpha: 1});
});

removeItElements.click(function() {
clickedIndex = removeItElements.index($(this));
bigbox = bigboxElements.eq(clickedIndex);
TweenLite.to(bigbox, 0.5, {autoAlpha: 0,opacity: 0});
});

这种方法的唯一问题是它非常依赖于 HTML 的布局顺序。

关于javascript - 添加和删​​除类不同的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30382841/

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