HTML轮播图片,实现占满整个页面的轮播图

用js实现轮播效果,不管图片尺寸是多少,都能自适应整个页面,下面是一个简单的demo。

HTML框架

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Index</title>
</head>

<body>
    <!-- 整体框架 -->
    <div class="carousel">
        <!-- 轮播图片 -->
        <img src="Images/1.jpg">
        <img src="Images/2.jpg">
        <img src="Images/3.jpg">
    </div>
</body>

</html>

CSS渲染

<style>
    body,
    html {
        height: 100%;
        margin: 0;
        padding: 0;
    }

    .carousel {
        /* 设置相对定位 */
        position: relative;
        height: 100%;
        width: 100%;
        /* 隐藏溢出部分 */
        overflow: hidden;
    }

    .carousel img:first-child{
        /* 设置绝对定位 */
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        /* 初始设置图片透明度为1 */
        opacity: 1;
        /* 设置渐变过渡效果 */
        transition: opacity 2s;
    }

    .carousel img:not(:first-child) {
        /* 设置绝对定位 */
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        /* 初始设置图片透明度为0 */
        opacity: 0;
        /* 设置渐变过渡效果 */
        transition: opacity 2s;
    }
</style>

JavaScript

<script>
    let carousel = document.querySelector('.carousel');
    let images = carousel.querySelectorAll('img');
    let currentImgIndex = 0;

    function showNextImage() {
        images[currentImgIndex].style.opacity = 0; // 隐藏当前图片
        currentImgIndex = (currentImgIndex + 1) % images.length; // 计算下一张图片的索引
        images[currentImgIndex].style.opacity = 1; // 显示下一张图片
    }

    // 设置定时器,每5秒切换图片
    setInterval(showNextImage, 5000);
</script>

运行结果

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值