原生JavaScript实现图片切换

原生JavaScript实现图片切换效果

效果:
在这里插入图片描述

html布局``

    <div class="slideshow">
        <!-- 图片区域 -->
        <div class="contentImg">
            <input type="image" src="img/prev.png" class="prev">
            <input type="image" src="img/next.png" class="next">
            <span id="countBtn">
                1/5
            </span>
        </div>
        <!-- 按钮区域 -->
        <div class="btns">
            <input type="button" class="circulation" value="循环状态">
            <input type="button" class="no_circulation" value="非循环状态">
        </div>
    </div>

css样式

body{
   
    margin: 0;
    padding: 0;
}
.slideshow{
   
    height:445px;
    width:650px;px
    margin:150px auto 0; /*设置主盒子居中离上边距150px*/
}
.contentImg{
   
    position: relative;
    height:400px;
    width: 650px;
    background-image: url(../img/a1.jpg);
    background-size: 100%; /*背景图片适应盒子大小*/
    transition: 2s; /*过渡时间变为2s*/
}
.contentImg input{
   
    height:60px;
    width:60px;
    top: 175px;
    position: absolute;
    outline: none; /*清除input框获取焦点的默认蓝色边框*/
}
.contentImg .prev{
   
    left: 10px;
}
.contentImg .next{
   
    right: 10px;
}
#countBtn{
   
    display: block; /*转换为块元素*/
    position:absolute;
    height: 28px;
    width:100px;
    border-radius: 14px;
    background-image:url(../img/backBotton.png);
    background-repeat: no-repeat;
    background-position-x: -5px; /*背景图片沿x轴偏移-5像素*/
    bottom: 10px;
    left: 50%;
    margin-left:-50px;
    text-align: center;
    line-height: 28px;
    font-size: 16px;
    font-weight: 600;
    color: white;
}
.btns{
   
    width:100%;
    text-align: center;
    margin-top: 15px;
}
.btns input{
   
    width: 190px;
    height: 30px;
    color: white;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    outline: none;
    background: #2164f3;
    border-radius: 10px;
    border: none;
}

布局完成!此时效果图是这样的

在这里插入图片描述
对于css,html这里不做过多讨论,比较陌生的地方已经加上注释了
下面的功能我们用JavaScript来实现他

接下来就是最重要的JavaScript代码,以下用两种不同的写法来实现这个功能

第一种,比较普遍的demo写法

第一步.把元素获取到

    var img = document.getElementsByClassName("contentImg")[0], //获取图片
        prev = document.getElementsByClassName("prev")[0], // 获取上一张的按钮
        next = document.getElementsByClassName("next")[0],//获取下一张的按钮
        span = document.getElementById("countBtn"), // 获取当前图片计数
        circulationNode = document.getElementsByClassName("circulation")[<
  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值