search
HomeWeb Front-endJS TutorialjQuery animation effect picture carousel implementation (with code)

This time I will bring you the implementation of jQuery animation effect picture carousel (with code). What are the precautions for the implementation of jQuery animation effect picture carousel. The following is a practical case, let's take a look. 1. Requirements Analysis

1. Provide many pictures of equal sizes and display them in a row.

2. There are two switch buttons on the left and right, used to control whether to display the previous or next picture.

3. There is an indicator "small circle" on the lower right to prompt which picture to display; you can also click it to switch pictures.

4. Every fixed time, the picture will automatically scroll.

5. When the mouse is placed on the picture, automatic scrolling will stop; when the mouse leaves, it will automatically play again after a fixed interval.

2. Code analysis

1. Use html code to build the framework

 
 <p> 
  </p>
         
  • jQuery animation effect picture carousel implementation (with code)
  •      
  • jQuery animation effect picture carousel implementation (with code)
  •      
  • jQuery animation effect picture carousel implementation (with code)
  •      
  • jQuery animation effect picture carousel implementation (with code)
  •      
  • jQuery animation effect picture carousel implementation (with code)
  •     
    

     

     

        
         
  •      
  •      
  •      
  •      
  •     
    

1> p with the id of container is the container for the entire carousel effect.
2> The ul whose id is content, the content stored in it is the scrolling picture displayed on the interface.

3> p with id btn, the two sub-elements inside are buttons used to switch between the previous and next pictures.

4> The ul whose id is indicator is used to display the indicator.

2. CSS code to change the display style

1> The following two lines of code clear the browser's default gap.

*{margin: 0; padding: 0;}

2> Set the style of the parent container.

#container 
{ 
 width:560px; 
 height: 300px; 
 margin: 100px auto; 
 position: relative; 
 overflow: hidden; 
}

Since the size of the displayed image is 560 If the child elements exceed the scope of the container, they will be hidden (Note: Since the displayed pictures are displayed in a row, if the overflow: hidden attribute is not added, the secret will be exposed. If this attribute is removed, the effect is as follows:).

#In other words, if the overflow: hidden attribute is not added, all the pictures will be displayed in a row.

The last one is the positioning attribute position: relative; Since container is the parent container, it should be set to relative, and if all its child elements are to be absolutely positioned, their positions should be Set to absolute. This is the so-called principle of "the son must be like the father". This is used in absolute positioning.

3> Set the style of content

#container #content 
{ 
 list-style: none; 
 width: 10000px; 
 position: absolute; 
 left:0; 
 top:0; 
} 
 
#container #content li 
{ 
 float:left; 
} 
 
#container #content li img 
{ 
 border: 0; 
}

Notice that the width attribute of content is set to 10000px, this is to ensure that it can store enough pictures. By default, all li in content are block-level elements, that is, they are arranged up and down; so a float:left is added to arrange them left and right. The parent element container is set with overflow: hidden, so only the first one of these pictures arranged left and right can be seen.
4> Set the style of the left and right switch buttons

#container #leftBtn 
{ 
 position: absolute; 
 width:45px; 
 height: 45px; 
 top:108px; 
 left: 20px; 
 background: url(images/icons.png) no-repeat 0 0; 
 cursor: pointer; 
} 
 
#container #rightBtn 
{ 
 position: absolute; 
 width:45px; 
 height: 45px; 
 top:108px; 
 right: 20px; 
 background: url(images/icons.png) no-repeat 0 -45px; 
 cursor: pointer; 
}

Notice that when obtaining the left and right buttons, they are taken from the same picture icons.png. It's just that the positions of the picture interceptions are inconsistent. This is the so-called "elf". In order to reduce the size of the picture, many small icons are placed on a picture, and then the desired part is obtained by positioning and intercepting. (Note: How to position the icon? 1. Write code and adjust slowly; 2. Use sprite cutting and positioning software, such as CSS Sprites, etc.). The picture design is roughly as follows:

This picture not only contains the left and right switching buttons, but also the indicator buttons, so when writing the indicator button When writing css code, you can also use this image.

4> Set the style of the indicator

#container #indicator 
{ 
 position: absolute; 
 right: 50px; 
 list-style: none; 
 bottom: 12px; 
} 
 
#container #indicator li 
{ 
 float: left; 
 cursor: pointer; 
 margin-left: 20px; 
 width:14px; 
 height: 14px; 
 background: url(images/icons.png) no-repeat -23px -127px; 
} 
 
#container #indicator li.current 
{ 
 background-position: -9px -125px; 
}

The background picture set by #indicator li in the code is the small hollow circle in the picture above, and the background picture set by #indicator li.current It’s the big solid circle in the picture above. So when you first start, the first one is selected by default.
3. Use JQuery to add interactive effects

1> Switch to the next image (click the button on the right)

$(function(){ 
 
 // 总的图片个数(用代码获取个数,扩展性比较强) 
 var totalCount = $("#container #content li").length; 
 // 当前处于第几个图片 
 var nowImage = 0; 
 $("#container #btn #rightBtn").click(rightBtnClick); 
<span> </span>function rightBtnClick(){ 
  if(!$("#container #content").is(":animated")){ 
   if(nowImage == totalCount - 1){ 
   <span> </span>nowImage = 0; 
<span>    </span>$("#container #indicator li").eq(nowImage).addClass("current").siblings().removeClass("current"); 
<span>    </span>$("#container #content").animate({"left": -560 * (totalCount -1 )}, 1000, function(){ 
    $("#container #content").css("left",0); 
   }); 
  } else { 
   nowImage++; 
   changeImage(); 
  } 
 } 
} 
});

changeImage function

function changeImage(){ 
 if(!$("#container #content").is(":animated")){ 
 <span> </span>$("#container #content").animate({"left": -560 * nowImage}, 1000); 
  $("#container #indicator li").eq(nowImage).addClass("current").siblings().removeClass("current"); 
 } 
}

代码中,当DOM元素加载完毕,就执行了$('#container #btn #rightBtn').click(rightClick), 也就是立刻执行了切换图片操作。在rightBtnClick函数中,先进行了content是否正在进行动画的判断,这样做的目的:防止动画在执行的过程,用户又进行强制的执行其他动画,会产生干扰,最终导致动画效果混乱。

如果有的话,则将标志变量nowImage指向下一个图片,并且执行changeImage函数中的代码:1. 将content中的所有图片左移一个图片大小的宽度;2.将指示器的图片也移动到对应的位置。

如果没有的话,并且图片现在是显示到了最后一个,则先执行动画,执行完毕后,立刻将content中所有的图片内容拉回到第一个,但是这里任然会穿帮,因为当前图片显示为最后一个后,你继续执行动画,是没有任何效果的,所以在这个动画执行期间是没有任何反应的,当动画时间执行完毕后,会突然在界面上出现第一个图片。

设计思想:为了解决这个问题,解决方案就是在这些图片之后追加一个与第一张相同的图片;这就是传统轮播的主要设计思想。所以当图片滚动到倒数第二章的时候;首先执行滚动动画,也就是滚动到预先准备的与第一张一模一样的图片,看起来似乎是滚动到了第一张,其实不然。在动画执行完毕后,立刻将content中所有的图片拉回到第一张。流程图如下:

所以此刻修改一点代码,在代码的开头追加第一张图片

/*克隆轮播的第一个li追加到最后*/ 
$("#container #content li").first().clone().appendTo($("#container #content"));

在rightBtnClick代码中,将nowImage == totalCount - 1 修改为 nowImage == totalCount - 2。
2> 切换上一张(点击左边按钮)

代码与点击右边按钮类似

$("#container #btn #leftBtn").click(function(){ 
 if(!$("#container #content").is(":animated")){ 
  if(nowImage == 0){ 
   nowImage = totalCount - 2; 
   $("#container #content").css("left",-560 * (totalCount - 1)); 
 
   $("#container #indicator li").eq(nowImage).addClass("current").siblings().removeClass("current"); 
 
   $("#container #content").animate({"left": -560 * nowImage}, 1000); 
  } else { 
   nowImage--; 
   changeImage(); 
  } 
 } 
});

3> 点击指示器按钮进行图片切换
它的设计思路,就是获取图片的索引,然后调用changeImage函数就可以了。

$("#container #indicator li").click(function(){ 
 nowImage = $(this).index(); 
 changeImage(); 
});

4> 添加定时执行动画的功能
也就是定时的调用点击右边按钮的代码;添加如下代码:

var timer = setInterval(rightBtnClick, 2000);

5> 鼠标悬停在图片上,停止滚动;鼠标离开图片后,继续滚动
也就是对定时器进行开启和关闭;添加如下代码:

$("#container").mouseenter(function(){ 
 clearInterval(timer); 
}).mouseleave(function(){ 
 timer = setInterval(rightBtnClick, 2000); 
});

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

jQuery实现图片轮播幻灯片效果

jquery拖拽效果实现方法

The above is the detailed content of jQuery animation effect picture carousel implementation (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

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