您的位置:首页技术文章
文章详情页

JS实现炫酷轮播图

【字号: 日期:2024-04-12 18:29:20浏览:44作者:猪猪

本文实例为大家分享了JS实现炫酷轮播图的具体代码,供大家参考,具体内容如下

效果图

<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <meta http-equiv='X-UA-Compatible' content='ie=edge'> <title>面试必备轮播图</title> <link rel='stylesheet' href='https://www.haobala.com/bcjs/demo.css' rel='external nofollow' ></head><body> <div id='wrap'> <img src='https://www.haobala.com/bcjs/images/1.png' alt=''> <img src='https://www.haobala.com/bcjs/images/2.png' alt=''> <img src='https://www.haobala.com/bcjs/images/3.png' alt=''> <img src='https://www.haobala.com/bcjs/images/4.png' alt=''> <img src='https://www.haobala.com/bcjs/images/5.png' alt=''> </div> <script src='https://www.haobala.com/bcjs/jquery.min.js'></script> <script src='https://www.haobala.com/bcjs/index.js'></script></body></html>

JS代码

var oImg = $(’img’);// 默认中间展示索引值为0的这张图片var curDisplay = 0;// 将图片分散排列// 获得图片个数var len = oImg.length;// 定时器var timer;function init() { initalCarousel(); bindEvent();}init();function initalCarousel() { // 获得中间图片 console.log($(’img’)) var hLen = Math.floor(oImg.length / 2); // rNum,lNum分别是分散在中间图片左右左右两侧的图片索引 var rNum, lNum; for (var i = 0; i < hLen; i++) { lNum = curDisplay - i - 1; // console.log(lNum) // 分别让分散在左右两侧的图片平移旋转 oImg.eq(lNum).css({ transform: ’translateX(’ + (-150 * (i + 1)) + ’px) translateZ(’ + (200 - i * 100) + ’px) rotateY(30deg)’ }); rNum = curDisplay + i + 1; // 如果运动到最后一张 循环运动 if (rNum > oImg.length - 1) { rNum -= oImg.length; } oImg.eq(rNum).css({ transform: ’translateX(’ + (150 * (i + 1)) + ’px) translateZ(’ + (200 - i * 100) + ’px) rotateY(-30deg)’ }); oImg.removeClass(’active’); } // 当前显示图片直接z轴向前移动 同时添加class名作为标记 oImg.eq(curDisplay).css({ transform: ’translateZ(300px)’ }).addClass(’active’);}// 点击事件function bindEvent() { // 在每一张图片上绑定上点击事件 oImg.on(’click’, function (e) { // 判断点击图片不是第一张显示图片 if (!$(this).hasClass(’active’)) { // 标记图片flag切换 // 改变当前显示图片索引 curDisplay = $(this).index(); initalCarousel(); } // 鼠标覆盖 清除自动轮播定时器 }).hover(function () { clearInterval(timer); // 鼠标移走 继续轮播 }, function () { play(); });}// 自动播放function play() { timer = setInterval(function () { if (curDisplay == len - 1) { curDisplay = 0; } else { curDisplay++; } initalCarousel(); }, 2000);}

CSS样式

*{ margin:0; padding:0;}.wrapper{ position: relative; transform-style: preserve-3d; perspective: 800px; /* border:1px solid black; */ height:200px; margin-top:200px;}.wrapper img{ position: absolute; left: 50%; top: 50%; width: 300px; height: 200px; margin-left: -150px; margin-top: -100px; border-radius: 8px; transition: transform 0.5s ease-in-out;}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好吧啦网。

标签: JavaScript
相关文章: