js轮播图练习

导读:本篇文章讲解 js轮播图练习,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

js轮播图练习

话不多说,直接上源码!

首先是HTML部分 index.html,主要用到了定位,父相对,子绝对。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>web轮播图练习</title>
    <link rel="stylesheet" href="css/index.css">

</head>
<body>
    <div class="box">
        <div class="inner-box">
            <img src="img/a1.jpg" id="imgHref">
            <span class="dot act"></span>
            <span class="dot"></span>
            <span class="dot"></span>
        </div>
    </div>
    <script src="js/imgLoop.js"></script>
</body>
</html>

css部分 index.css

*{
    margin: 0;
    padding: 0;
}
/*清空默认样式*/

body{
    width: 1920px;/*默认网页1920px宽*/
    height:auto;
    background-color: bisque;
}
.box{
    width: 100%;
    height: auto;
}
.box .inner-box{
    width: 900px;
    height: 490px;
    margin: 40px auto;
    position: relative;/*父盒子相对定位,便于dot原点定位*/
}
.box .inner-box span{
    display: inline-block;
    height: 16px;
    width: 16px;
    border-radius: 50%;

    background-color: transparent;
    position: absolute;/*dot原点相对于父盒子绝对定位*/
    /*位置left right都是相对于inner-box的宽高乘以比例*/
    left: 80%;
    top: 90%;
    cursor: pointer;
    box-shadow: 0px 0px 2px 2px darkgray;
}
/*通过伪类对每个span元素定位*/
.box .inner-box span:nth-of-type(2){
    left: 86%;
    top: 90%;
}
.box .inner-box span:nth-of-type(3){
    left: 92%;
    top: 90%;
}
.box .inner-box .dot:hover{
    background-color:azure;
}
/*切换图标原点时。。*/
.box .inner-box .act{
    background-color: azure;
}

然后是js部分 imgLoop.js
需要注意的是,如果使用img标签,那么你可以通过getAttributesetAttribute分别来获取value值和设定某个value值。然后就是一些获取元素的方式(类属性,ID属性,css选择器都可以),不过多赘述。

var spanList =document.getElementsByClassName("dot");// 获取dot类属性的标签元素
var imgHref = document.getElementById("imgHref");//根据id获取图片元素
var spanPre;// 记录一开始就已经存在act属性的span索引值 即一开始显示的原点
var spanSuf;// 记录经过点击事件改变的原点的span索引值
for (let i = 0; i < spanList.length; i++) {
    for (let j = 0; j < spanList.length; j++) {
        if(spanList.item(j).classList.contains("act")){
            spanPre = j;
            break;//找到点击之前显示的原点,然后用spanPre记录下
        }
    }
    spanList.item(i).onclick=function () {
        if(! spanList.item(i).classList.contains("act")){
            //移除之前已经存在的原点位置,改为现在点击后希望显示的图片
            spanList.item(spanPre).classList.remove("act");
            spanList.item(i).classList.add("act");
            //修改图片路径 
            imgHref.setAttribute("src","img/a"+(i+1)+".jpg");
            //记录当前点击的索引值给 spanSuf,同时修改spanPre的值为现在修改后的索引值
            spanSuf =i;
            spanPre = spanSuf;
        }
    }
}

最后是图片
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
效果图
在这里插入图片描述

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

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/105191.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!