在SCSS中动态堆叠图像

时间:2019-07-01 10:01:45

标签: javascript jquery html css sass

我想在SCSS中创建以下布局: enter image description here

由于图像具有动态编号,因此它可以是4,5或2张图像,因此我无法对负数top或translateY属性进行硬编码。因此,我需要在SCSS中使用foreach循环,以便为这些图像分配不同的顶部。是否可以在SCSS中创建这样的布局,还是我需要使用JS?

这是我目前拥有的,如您所见,我只能移动第二个元素,而第三个元素已经translateY(-100%)

.layers__img {
  position: relative;
  top: 0;
}
.layers__img:not(:first-child) {
  transform: translateY(-50%);
  transition: transform 0.5s ease-in;
}
<div class="layers">
            <div class="layers__img" id="layer-1">
            <img src="https://placeimg.com/640/480/any">
        </div>
            <div class="layers__img" id="layer-2">
            <img src="https://placeimg.com/640/480/any">
        </div>
            <div class="layers__img" id="layer-3">
            <img src="https://placeimg.com/640/480/any">
        </div>
    </div>

1 个答案:

答案 0 :(得分:2)

在下面尝试一下:

let layers = $('.layers__img');
$.each( layers, function( key, value ) {
  var percent = 50;
  if(key != 0) {
    $('img',value).css('transform', 'translateY(-'+percent * key+'%)');
  }
});
.layers__img {
  position: relative;
  top: 0;
}
.layers__img:not(:first-child) {
  transition: transform 0.5s ease-in;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="layers">
        <div class="layers__img" id="layer-1">
            <img src="https://placeimg.com/640/480/any" width="100px">
        </div>
        <div class="layers__img" id="layer-2">
            <img src="https://placeimg.com/640/480/any"  width="100px">
        </div>
        <div class="layers__img" id="layer-3">
            <img src="https://placeimg.com/640/480/any"  width="100px">
        </div>
        <div class="layers__img" id="layer-3">
            <img src="https://placeimg.com/640/480/any"  width="100px">
        </div>
        <div class="layers__img" id="layer-3">
            <img src="https://placeimg.com/640/480/any"  width="100px">
        </div>
 </div>