欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

js实现适合新闻类图片的轮播效果

程序员文章站 2023-11-11 14:15:52
话不多说,请看代码:

话不多说,请看代码:

<!doctype html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>picture carousel</title>
<style>
*
{
 margin: 0;
 padding: 0;
}
.carousel-container
{
 overflow: hidden;
 width: 405px;/* 130*3+5*3 = 405 */
 height: 150px;
 margin: 50px auto;
 background-color: #2c2c2c;
}
.carousel-area
{
 width: 1350px;/* 675*2 = 1350 */
 height: 150px;
}
.carousel-ul
{
 float: left;
 overflow: hidden;
 width: 675px;/* 130*5+5*5 = 675 */
 height: 150px;
}
.carousel-ul li
{
 float: left;
 overflow: hidden;
 width: 130px;
 height: 130px;
 margin: 10px 5px 10px 0;
 list-style-type: none;
}
 </style>
</head>
<body>
 <div class="carousel-container">
 <div class="carousel-area">
 <ul class="carousel-ul" id="carousel-ul-1">
 <li><img src="img/1.gif" alt=""></li>
 <li><img src="img/2.jpg" alt=""></li>
 <li><img src="img/3.jpg" alt=""></li>
 <li><img src="img/4.jpg" alt=""></li>
 <li><img src="img/5.gif" alt=""></li>
 </ul>
 </div>
 </div>
<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script>
 $(document).ready(function() {
 var carousel_interval_id, //interval id
 start_carousel_flag = false, //是否开始interval
 carousel_speed = 50, //滚动速度(px/s),carousel_speed=1000/interval时间间隔。
 start_interval = function() { //执行interval
  start_carousel_flag = true;
  carousel_interval_id = setinterval(function() {
  var margin_left = $('.carousel-area').css('margin-left');
  $('.carousel-area').css('margin-left', (parseint(margin_left) - 1) + 'px'); //不断左移1px
  if (parseint($('.carousel-area').css('margin-left')) <= -($('.carousel-ul').width())) { //轮播部分超出容器后复位
   $('.carousel-area').css('margin-left', 0);
  }
  }, 1000 / carousel_speed)
 },
 end_interval = function() { //停止interval
  start_carousel_flag = false;
  carousel_interval_id = clearinterval(carousel_interval_id);
 }
 $('.carousel-area').append('<ul class="carousel-ul">' + $('.carousel-ul').html() + '</ul>'); //复制carousel-ul,填补左移后出现的无内容区域,以此完成循环
 start_interval();
 $('.carousel-area').hover(
 function() { //鼠标悬停事件
  if (start_carousel_flag) { //已经开始interval
  end_interval();
  }
 },
 function() { //鼠标离开事件
  if (!start_carousel_flag) { //没有开始interval
  start_interval();
  }
 }
 )
})
</script>
</body>
</html>

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!