加入收藏 | 设为首页 | 会员中心 | 我要投稿 信阳站长网 (https://www.0376zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 编程要点 > 语言 > 正文

用jquery怎样写一个轮播图?轮播图实例代码分享

发布时间:2022-03-24 14:23:15 所属栏目:语言 来源:互联网
导读:在制作网页页面时,轮播图效果是比较常见的,想要实现轮播图效果的方法很多,本文主要介绍的使用jQuery实现轮播图,以下是实现代码,感兴趣的朋友可以了解看看。 介绍:这里是我使用了计时器的方式实现图片每隔几秒切换然后添加了两个按钮用于上一张和下一张
       在制作网页页面时,轮播图效果是比较常见的,想要实现轮播图效果的方法很多,本文主要介绍的使用jQuery实现轮播图,以下是实现代码,感兴趣的朋友可以了解看看。
 
       介绍:这里是我使用了计时器的方式实现图片每隔几秒切换然后添加了两个按钮用于上一张和下一张的切换
       1、导入jQuery文件
<script src="jquery-3.5.1.js"></script>
       2、设置图片的样式
<style>
  *{
   margin: 0;
   padding: 0;
  }
  #box{
   width: 300px;
   height: 300px;
   border: 2px solid red;
  }
  #box img{
   position: absolute;
   display: none;
  }
  #box :first-child{
   display: block;
  }
  .page{
   list-style: none;
   display: flex;
   width: 300px;
   justify-content: space-around;
  }
  .page li{
   border: 1px solid red;
   border-radius: 50%;
   width: 20px;
   height: 20px;
   text-align: center;
 
  }
  .active{
   background: red;
  }
 </style>
 <script src="./jquery.js"></script>
</head>
<body>
 <div id="box">
  <img src="./img/1.jpg" alt="">
  <img src="./img/2.jpg" alt="">
  <img src="./img/3.jpg" alt="">
  <img src="./img/4.jpg" alt="">
 </div>
 <ul class="page" id="page" >
  <li class="active">1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
 </ul>
<button id="next">下一张</button>
<button id="prev">上一张</button>
       3 进行图片的轮播实现方式
/*
 绝对定位 -- 摞起来
 通过下标 -- 显示当前 --其他兄弟 隐藏
*/
  <script>
   var index=0;
    // 移动方法
   function move(){
    index++;
    if (index>=$("#box img").length) {
     index=0;
    }
    $("#box img").eq(index).show().siblings().hide();
    $("#page li").eq(index).addClass("active").siblings().removeClass("active");
   }
   //计时器的实现方法
   var t=setInterval(move,2000);
   //鼠标移动到图片会停止离开继续轮播
   $("#box").hover(function(){
    clearInterval(t)
   },function(){
    t=setInterval(move,2000)
   })
 
   $("#page li").click(function(){
    index= $(this).index() ;
    $("#box img").eq(index).show().siblings().hide();
    $("#page li").eq(index).addClass("active").siblings().removeClass("active");
   })
   //下一张的点击
   $("#next").click(function(){
    move();
   })
   //上一张的点击
   $("#prev").click(function(){
    index--;
    // 判断如果下标超过固有图片的数量时,从头开始轮播
    if (index<0) {
     index=$("#box img").length-1;
    }
    $("#box img").eq(index).show().siblings().hide();
    $("#page li").eq(index).addClass("active").siblings().removeClass("active");
   })

(编辑:信阳站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读