javascript实现图片轮播效果

目录

效果预览

本章将实现以下效果:
这里写图片描述

HTML代码

<div class="wrap" id='wrap'>
    <ul id="pic" class="pic">
        <li><img src="image/picRoller1.jpg" alt=""></li>
        <li><img src="image/picRoller2.jpg" alt=""></li>
        <li><img src="image/picRoller3.jpg" alt=""></li>
    </ul>
    <ul id="list" class="list">
        <li class="on">1</li>
        <li>2</li>
        <li>3</li>
    </ul>
</div>

CSS代码

.wrap {
    height: 360px;
    width: 990px;
    overflow: hidden;
    position: relative;
    margin-left: 190px;
    margin-top: 15px;
    top: 10px;
    bottom: 5px;
}

.wrap img {
    height: 360px;
    width: 990px;
}

.pic {
    position: absolute;
}

.list {
    position: absolute;
    right: 5px;
    bottom: 10px;
}

.list li {
    height: 20px;
    width: 20px;
    background: white;
    margin-left: 5px;
    color: #000;
    float: left;
    line-height: 20px;
    text-align: center;
    cursor: pointer;
    list-style: none;
}

.list .on {
    background: #E97305;
    color: #fff;
}

JavaScript代码

window.onload = function () {
    var wrap = document.getElementById('wrap'),
        pic = document.getElementById('pic').getElementsByTagName("li"),
        list = document.getElementById('list').getElementsByTagName('li'),
        index = 0,
        timer = null;


    // 遍历所有数字导航实现划过切换至对应的图片
    for (var i = 0; i < list.length; i++) {
        list[i].onmouseover = function () {
            clearInterval(timer);
            index = this.innerText - 1;
            changePic(index);
        };
    }

    function autoPlay () {
        if (++index >= pic.length) index = 0;
        changePic(index);
    }

    // 定义图片切换函数
    function changePic (curIndex) {
        for (var i = 0; i < pic.length; ++i) {
            pic[i].style.display = "none";
            list[i].className = "";
        }
        pic[curIndex].style.display = "block";
        list[curIndex].className = "on";
    }
    // 定义并调用自动播放函数
    timer = setInterval(autoPlay, 3000);

    // 鼠标划过整个容器时停止自动播放
    wrap.onmouseover = function () {
        clearInterval(timer);
    };

    // 鼠标离开整个容器时继续播放至下一张
    wrap.onmouseout = function () {
        timer = setInterval(autoPlay, 3000);
    };
};
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值