连续图像转盘(又名滑块)是在您的网站上展示多个图像、内容等的好方法。
创建滑块是一项相当简单的任务。我们今天将使用jQuery创建一个可以处理您向它抛出的任何数量的图像的查询。
1.在滑块中插入图像列表。
- <div id="slider">
- <ul>
- <li><img src="1.jpg" alt="Image Alt" /></li>
- <li><img src="2.jpg" alt="Image Alt" /></li>
- <li><img src="3.jpg" alt="Image Alt" /></li>
- <li><img src="4.jpg" alt="Image Alt" /></li>
- <li><img src="5.jpg" alt="Image Alt" /></li>
- </ul>
- </div>
2.将下一个/上一个控制按钮添加到滑块中。
- <p id="links">
- <a href="#" id="previous">Prev</a>
- <a href="#" id="next">Next</a>
- </p>
3.在文档中加载所需的jQuery库和jQuery轻松插件(用于轻松功能)。
- <script src="/path/to/cdn/jquery.min.js" defer></script>
- <script src="/path/to/jquery.easing.min.js" defer></script>
4.滑块和控件的主要CSS样式。
- /* Core Styles */
- #slider {
- width:400px;
- overflow:hidden;
- border: 10px solid #4C4C4C;
- height:266px;
- position:relative;
- margin:auto;
- }
- #slider ul {
- list-style-type: none;
- margin: 0;
- padding: 0;
- position: absolute;
- top: 0;
- left: 0;
- display: flex;
- }
- #slider ul li img {
- display: block;
- }
- /* Control Styles */
- #links {
- width:420px;
- display: flex;
- margin: 0 auto;
- }
- #links a {
- display:block;
- width:210px;
- background:#6C0204;
- height:50px;
- line-height:50px;
- color:#D5D5D5;
- text-decoration:none;
- text-align:center;
- }
- #links a:hover {
- background:#A51D1F;
- color:#fff;
- }
5.用于激活滑块的核心JavaScript(jQuery脚本)。
- $(window).on('load', function() {
- "use strict";
- const imageCount = $('#slider ul li').length;
- const imageWidth = $('#slider ul li img').first().width();
- const totalWidth = (imageWidth * imageCount) + 'px';
- let leftPosition = 0;
- let counter = 0;
- $('#slider ul').css('width', totalWidth);
- // next button
- $('#next').click(function() {
- counter++;
- if (counter === imageCount) {
- $('#slider ul').clone().appendTo('#slider');
- $('#slider ul').last().css('left', imageWidth + 'px');
- leftPosition = `-${totalWidth}`;
- $('#slider ul').last().animate({
- left: 0
- }, 700, 'easeInQuad');
- $('#slider ul').first().animate({
- left: leftPosition
- }, 700, 'easeInQuad', function() {
- $('#slider ul').first().remove();
- });
- counter = 0;
- } else {
- leftPosition = `-${counter * imageWidth}px`;
- $('#slider ul').animate({
- left: leftPosition
- }, 700, 'easeInQuad');
- }
- });
- // previous button
- $('#previous').click(function() {
- counter--;
- if (counter < 0) {
- counter = imageCount - 1;
- $('#slider ul').clone().appendTo('#slider');
- $('#slider ul').last().css('left', `-${totalWidth}`);
- leftPosition = `-${counter * imageWidth}px`;
- $('#slider ul').last().animate({
- left: leftPosition
- }, 700, 'easeInQuad');
- $('#slider ul').first().animate({
- left: imageWidth + 'px'
- }, 700, 'easeInQuad', function() {
- $('#slider ul').first().remove();
- });
- } else {
- leftPosition = `-${counter * imageWidth}px`;
- $('#slider ul').animate({
- left: leftPosition
- }, 700, 'easeInQuad');
- }
- });
- });