简体   繁体   English

如何使用 JS 在页面加载时为 div 滚动到其最后一个子项设置动画?

[英]How to animate a div scrolling to its last child on page load using JS?

I am trying to get an animation of a div scrolling down to its last child when the page is loaded to create a slide show.我试图让一个 div 的 animation 在加载页面以创建幻灯片放映时向下滚动到其最后一个子级。

Here is the div itself这是 div 本身

<section class="carousel" id="carousel">
  <div class="images-container">
    <a href="#"><img src="img/berlin1.jpg" alt="pic 1" class="auto-resize"></a>
    <a href="#"><img src="img/berlin2.jpg" alt="pic 1" class="auto-resize"></a>
    <a href="#"><img src="img/berlin3.jpg" alt="pic 1" class="auto-resize"></a>
    <a href="#"><img src="img/berlin4.jpg" alt="pic 1" class="auto-resize"></a>
    <a href="#" id="lastimage"><img src="img/berlin5.jpg" alt="pic 1" class="auto-resize"></a>
  </div>
</section>
.carousel {
  position: relative;
  z-index: 1;
  grid-area: crsl;
  overflow-y: scroll;
  height: 100%;
  overflow: -moz-scrollbars-none;
}

.carousel::-webkit-scrollbar { width: 0 !important }

Ultimately what I am trying to achieve is an automatic slideshow in this div when the page loads.最终我想要实现的是页面加载时在这个 div 中的自动幻灯片。

If you don't need the scroll bar besides the automatic slide show you could remove the scrollbar by giving the div min-content height and then using a translateY transform and a transition to make the images slide through your section.如果除了自动幻灯片放映之外您不需要滚动条,您可以通过提供 div min-content 高度然后使用 translateY 转换和转换使图像在您的部分中滑动来删除滚动条。

I've set up an example:我已经建立了一个例子:

 let imagesContainer = document.getElementById("images-container"); let lastImgHeight = 0; window.onload = () => { lastImgHeight = document.getElementById("last-img").clientHeight; document.getElementById("carousel").style.maxHeight = `${lastImgHeight}px`; }; setTimeout(() => { imagesContainer.classList.add("images-container-animate"); imagesContainer.classList.remove("images-container"); imagesContainer.style.transform = `translateY(${-(imagesContainer.clientHeight - lastImgHeight)}px)`; }, 100);
 .images-container { height: min-content; display: flex; flex-direction: column; transform: translateY(0); }.images-container-animate { transition: transform 6s; transition-timing-function: linear; display: flex; flex-direction: column; } #carousel { overflow-y: hidden; }
 <section class="carousel" id="carousel"> <div class="images-container" id="images-container"> <a href="#"><img src="https://cdn.pixabay.com/photo/2020/03/10/08/39/cloud-4918228_960_720.jpg" alt="pic 1"></a> <a href="#"><img src="https://cdn.pixabay.com/photo/2020/03/30/17/15/funes-4984899_960_720.jpg" alt="pic 1"></a> <a href="#"><img src="https://cdn.pixabay.com/photo/2020/03/31/11/59/sunrise-4987384_960_720.jpg" alt="pic 1" id="last-img"></a> </div> </section>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM