jQuery 上下动画

jQuery animate up and down

我正在构建一个带有图像网格的网页,当用户单击图像时,透明层会向上滑动,并带有包含有关图像的一些信息的动画。这适用于我在下面制作的脚本。

但我需要改进它,因为当用户点击第二张图片时,之前的透明层应该向下滑动,这也有效,但如果用户点击同一层,动画只会向上滑动然后向下滑动。我的问题是是否可以改进我的脚本来处理这个问题。

我的第二个问题是,如果任何层已经打开,脚本会通过向下滑动开始,但这会影响所有 div 标签还是只影响打开的标签?我想如果我有一个大网格并且脚本向下滑动所有层,尽管只有一个是可见的,但会有一些性能问题!?我的代码是否正常,或者是否有任何可以改进的缺陷?

JQuery:

$(document).ready(function(){
$(".outer").click(function(){ 
    $(".inner").animate({height:'-=100%'},250);
    $(this).children(".inner").animate({height:'+=100%'},250);
});
});

HTML:

<div class='outer'>
<img src="image-1.png" class="click">
<div class='inner'><h1>Cover 1</h1></div>
</div>
<div class='outer'>
<img src="image-2.png" class="click">
<div class='inner'><h1>Cover 2</h1></div>
</div>
<div class='outer'>
<img src="image-3.png" class="click">
<div class='inner'><h1>Cover 3</h1></div>
</div>

CSS:

.outer {
height: auto;
background: yellow;
position:relative;
width: 300px;
}

.outer img {
display: block;
}

.inner {
position: absolute;
bottom: 0;
height:0;
width: 100%;
background:rgba(0, 0, 0, 0.5);
}

这是您要实现的目标的简短示例。

$(".box").removeClass('animate');

它首先删除每个 .box

上的所有 class .animate
$(this).addClass('animate');

然后,它仅在单击的元素上设置 class。

.animateclass可以是任何东西,只要它只包含元素正常状态的变化。

过渡可以很容易地改变。过渡非常方便:

The transition CSS property is a shorthand property for transition-property, transition-duration, transition-timing-function, and transition-delay. It enables you to define the transition between two states of an element. Different states may be defined using pseudo-classes like :hover or :active or dynamically set using JavaScript.

Mozilla Developer Network 阅读更多相关信息。

更新

    if ($(this).hasClass('animate')) {
        $(".box").removeClass('animate');
      } else {
        $(".box").removeClass('animate');
        $(this).addClass('animate');
      }

这将适用于下次点击。

$(".box").click(function(e) {
  e.preventDefault;
  if ($(this).hasClass('animate')) {
    $(".box").removeClass('animate');
  } else {
    $(".box").removeClass('animate');
    $(this).addClass('animate');
  }
});
.box {
  background: red;
  width: 100px;
  height: 100px;
  margin: 10px;
  top: 0;
  transition: margin-left .5s ease-in-out;
}
.animate {
  margin-left: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>