javascript - 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.
Here is the div itself
<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 min-content 高度然后使用 translateY 变换和过渡使图像在您的部分中滑动来移除滚动条。
我已经建立了一个例子:
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>
推荐阅读
- java - Okhttp3:使用 HeaderInterceptor 需要帮助
- python - Python gTTS几个mp3文件问题
- java - 如何使recyclerview中的进度条不可见
- android - 如何连接一些 Firebase 数据库,其 google-services.json 未添加到我的应用中
- postgresql - 将数据库从 sqlite 转换为 postgres 的问题
- c# - 使用嵌套括号拆分字符串,但将它们保留在自己的组中
- c++ - 如何创建智能指针向量
- javascript - 根据其他对象值更改对象键
- flutter - 如何在颤动中通过滚动控制器中途调用函数
- html - 切换时图标不旋转