js实现适合新闻类图片的轮播效果
作者:Lasy
本文主要分享了js实现适合新闻类图片轮播效果的示例代码,具有一定的参考价值,下面跟着小编一起来看下吧
话不多说,请看代码:
<!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>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持脚本之家!