search
HomeWeb Front-endJS TutorialjQuery implements animated carousel ads

jQuery implements animated carousel ads

Apr 24, 2018 am 10:42 AM
jqueryadvertiseEffect

This time I will bring you jQuery to implement animated carousel ads. What are the precautions for jQuery to implement animated carousel ads? 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 implements animated carousel ads
  •      
  • jQuery implements animated carousel ads
  •      
  • jQuery implements animated carousel ads
  •      
  • jQuery implements animated carousel ads
  •      
  • jQuery implements animated carousel ads
  •     
    

     

     

        
         
  •      
  •      
  •      
  •      
  •     
     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> 切换下一张(点击右边按钮)

$(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 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); 
});

精彩专题分享:jQuery图片轮播 JavaScript图片轮播 Bootstrap图片轮播

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

推荐阅读:

jQuery实现旋转幻灯片轮播效果(附代码)

jquery miniui表格控件与合并单元格实现方法

The above is the detailed content of jQuery implements animated carousel ads. 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
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

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

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

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: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

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 Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

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.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

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.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

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.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)