微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

html中图片滑动效果代码

在网站制作中,图片滑动效果可以为内容增加动态感,吸引用户的注意力。下面我们介绍一下如何使用HTML制作图片滑动效果。 首先,我们需要定义一个图片容器,通过CSS来定义其宽高和样式。接下来,在容器中放置要滑动的图片,使用自适应图片可以保证在不同大小的设备上都有良好的展示效果

首先,定义一个图片容器:

<div class="slider">
    <img src="img1.jpg">
    <img src="img2.jpg">
    <img src="img3.jpg">
    <img src="img4.jpg">
</div>

html中图片滑动效果代码

接下来,定义CSS样式,让容器的样式和位置合理:

.slider {
    width: 100%;
    height: 400px;
    overflow: hidden;
    margin: 0 auto;
    position: relative;
}

img {
    width: 100%;
    height: 400px;
    position: absolute;
    top: 0;
    left: 0;
    transition: all 0.5s ease-in-out;
}

img:nth-child(2) {
    left: 100%;
}

img.active {
    left: 0;
}

img.prevIoUs {
    left: -100%;
}

img.next {
    left: 100%;
}

接下来,定义JavaScript代码

const images = document.querySelectorAll(".slider img");

let index = 0;

setInterval(() => {
    const prevIoUsIndex = index === 0 ? images.length - 1 : index - 1;
    const nextIndex = index === images.length - 1 ? 0 : index + 1;

    images[prevIoUsIndex].classList.remove("prevIoUs");
    images[nextIndex].classList.remove("next");

    images[index].classList.add("active");
    images[prevIoUsIndex].classList.add("next");
    images[nextIndex].classList.add("prevIoUs");

    index = nextIndex;
},5000);
这段JavaScript代码使用setInterval循环,每次执行时改变图片的类,实现图片的滑动效果。 通过实现这段代码,我们可以实现图片滑动效果,让页面动态起来,提高用户的阅读体验,也让网站更加生动活泼。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐