Carousel is the second dynamic effect implemented when learning jquery, and it is also the one that takes the longest to learn. In the process of implementing the carousel, we always encounter various problems. I have consulted many people and asked many times. Today, I dare not boldly say that I can write a carousel right away.
I hope to record some thinking processes through essays.
The first is the html structure, a simple carousel, a seamless carousel of single pictures, mainly divided into three layers: div>ul>li, and the img picture inside li.
Secondly, css style: div fixed width and height, overflow: hidden; the width of ul is recommended to be obtained dynamically (the next step will be about how to obtain it); regarding li, I am used to using floating, so that they can be arranged in order, on the ul Remember to clear float (clear: both).
The important thing is the jquery method, the main ones used are animate(), setInterval(), hover(). Before writing the method, let’s clarify the logic of the dynamic effect: the pictures slide from right to left in a loop. When the last picture is slid, the first picture is displayed, and so on.
1. Get the number of li length and width
var len=$('li').length,
liWidth=$('li').width,
Because it is a seamless carousel, we have to do something to achieve a natural transition. When the picture slides to the last one, how can we naturally transition to the first one? At this time, if the third picture Just one piece after the last one is fine. Therefore, we need to clone the first piece and append it to the end of li
$('li:first').clone().appendTo('ul')
2. Get the width of ul: the width of ul is equal to the width of all li plus the width of the cloned li
ulWidth=liWidth*(len+1)
It seems that the preparations are done, so the next step is to try to make him move. The first thing that comes to mind is the animate() method:
animate( properties [, duration ] [, easing ] [, complete ] ),
The first parameter properties: css attributes and value objects, which determine the effect of the animation, whether it is up and down or left and right;
The second parameter duration: the time to complete an animation, the default is 400, the unit is milliseconds;
The third parameter easing: the easing function used for animation transition, the default is swing (linear, swing), this parameter is generally not used;
The fourth parameter complete: refers to the operation performed after completing the animation.
Our animation is from right to left, so we can achieve it by changing the margin-left value of ul
$('ul').animate({ 'marign-left': -liWidth*index },3000,function(){ if(index==len){ index=0; $('ul').css({'margin-left':'0px'}) } })
The index refers to the index value of li. When the index value of li is equal to the length value of li, that is, the animation has been executed to the last picture, then directly set the margin-left of ul to 0 and the index value of li Also 0.
There is another hidden danger in this, which I won’t mention for now.
Next step, when the mouse leaves the div, the picture will automatically play. This is to use hover() and setInterval()
setInterval() is explained by W3C as follows: call a function or calculate an expression according to the specified period (in milliseconds). The function is called continuously until clearInterval() is called or the window is closed.
var autoPlay; $('div').hover(function(){ clearInterval(autoPlay); },function(){ autoPlay=setInterval(function(){ $('ul').animate({ 'marign-left': -liWidth*index },3000,function(){ if(index==len){ index=0; $('ul').css({'margin-left':'0px'}); index++; } }); },3000) }).trigger('mouseleave');
In this way, an automatic playback function seems to be implemented, but we can also find a bug. The first frame seems to stay a bit long. Why?
This problem was solved yesterday. When the last picture is executed, its index immediately changes to 0, and then it will be executed twice. Therefore, in this judgment, we need to let it when the index is 0. Add 1, index++, and put it under the judgment condition.
There is another problem, which I discovered yesterday. There are two times in this carousel, one is the animation execution time, and the other is the playback time. The former time must be smaller than the latter time. The reason is that js The execution order is top-down. If the times are consistent or the latter time is smaller than the former, then within this time difference, the animation will not be able to enter the judgment conditions and will continue to play, so the carousel will fail. That’s it for today. Next time I share it, I’ll add a carousel effect of left and right arrows and hover dots.
Attached is the complete code:
<html"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>轮播</title> <style> body,p,form,input,button,dl,dt,dd,ul,ol,li,h1,h2,h3,h4{margin:0;padding:0;list-style:none;} body,button,input,select,textarea{font:12px Arial, Helvetica, sans-serif;color:#333;} input,select,textarea{font-size:100%;} .clearfix:after{display:block;content:".";height:0;visibility:hidden;clear:both;font-size:0;line-height:0;} .clearfix{*zoom:1;} .big-screen{width: 100%; height: 400px; overflow: hidden; margin: 40px 0;} .pic-list{height: 400px;} .pic-list li{float: left; width: 1920px; height: 400px;} </style> </head> <body> <div class="big-screen"> <ul class="pic-list clearfix"> <li> <a href="javascript:;"> <img src="/static/imghwm/default1.png" data-src="http://fed.yhd.cn:9000/1920x400/27ae60xfff" class="lazy" alt="picture" style="max-width:90%" style="max-width:90%"/> </a> </li> <li> <a href="javascript:;"> <img src="/static/imghwm/default1.png" data-src="http://fed.yhd.cn:9000/1920x400/ae273axfff" class="lazy" alt="picture" style="max-width:90%" style="max-width:90%"/> </a> </li> <li> <a href="javascript:;"> <img src="/static/imghwm/default1.png" data-src="http://fed.yhd.cn:9000/1920x400/2757aexfff" class="lazy" alt="picture" style="max-width:90%" style="max-width:90%"/> </a> </li> <li> <a href="javascript:;"> <img src="/static/imghwm/default1.png" data-src="http://fed.yhd.cn:9000/1920x400/ae7d27xfff" class="lazy" alt="picture" style="max-width:90%" style="max-width:90%"/> </a> </li> </ul> </div> </body> <script type="text/javascript" src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ var ul=$('.pic-list'), li=ul.find('li'), liW=li.outerWidth(true), liLen=li.length, index=0, autoPlay; li.first().clone().appendTo(ul); ul.css({'width':liW*(liLen+1),'margin-left':-liW*index}); function play(){ if(!ul.is('animated')){ ul.stop().animate({ 'margin-left':-liW*index },480,function(){ if(index>liLen){ index=0; ul.css({'margin-left':-liW*index}); index++; } }); } } $('.big-screen').hover(function(){ clearInterval(autoPlay); },function(){ autoPlay=setInterval(function(){ play(); index++; },500) }).trigger('mouseleave'); }) </script> </html>
The above is the entire content of this article, I hope it will be helpful to everyone’s study.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools