This article mainly introduces in detail the js implementation of the left-to-right sliding carousel effect. It has a certain reference value. Interested friends can refer to the
carousel chart. Let the pictures slide automatically every few seconds to achieve the effect of pictures playing in turn. In terms of effects, carousels can be either sliding or gradual. The sliding carousel is the effect of pictures sliding in from left to right. The gradual carousel is the effect of pictures gradually being displayed based on transparency. What I’m talking about here is the method to achieve the first effect.
Principle
Pictures of the same size are combined into a column, but only one of the pictures is displayed, and the rest are hidden. Change the display by modifying the left value picture.
Click to view the effect
html part
nav is the total container, No. One ul list #index is a list of small dots. Whichever dot is covered by the mouse will display the picture. on is a class that adds a background color attribute to the small dots; the second ul list #img is a list of pictures.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Carousel Figure</title> <link rel="stylesheet" href="style.css" rel="external nofollow" > </head> <body> <!--从左向右滑动--> <nav> <ul id="index"> <li class="on"></li> <li></li> <li></li> <li></li> <li></li> </ul> <ul id="img"> <li><img src="/static/imghwm/default1.png" data-src="../images/img1.jpg" class="lazy" alt="img1"></li> <li><img src="/static/imghwm/default1.png" data-src="../images/img2.jpg" class="lazy" alt="img2"></li> <li><img src="/static/imghwm/default1.png" data-src="../images/img3.jpg" class="lazy" alt="img3"></li> <li><img src="/static/imghwm/default1.png" data-src="../images/img4.jpg" class="lazy" alt="img4"></li> <li><img src="/static/imghwm/default1.png" data-src="../images/img5.jpg" class="lazy" alt="img5"></li> </ul> </nav> <script src="script.js"></script> </body> </html>
css part
The image sizes are all 720*405, you need to pay attention to the following points here:
ul#The img list is absolutely positioned relative to nav. The length of #img must be set to the total width of all images so that the images can be displayed side by side;
The width of the total container nav must be set to the width of the picture 720px, that is, only one picture can be displayed, and the part beyond the width is hidden, that is, overflow: hidden;
The small dot list should be displayed above the picture list, so Set the z-index of #img: -1;
The small dot list is composed of a series of li by changing the border style, so you only need to change the background color to achieve the effect of moving the small dots.
*{ margin:0; padding:0; } nav{ width: 720px; height: 405px; margin:20px auto; overflow: hidden; position: relative; } #index{ position: absolute; left:320px; bottom: 20px; } #index li{ width:8px; height: 8px; border: solid 1px gray; border-radius: 100%; background-color: #eee; display: inline-block; } #img{ width: 3600px;/*不给宽高无法移动*/ height: 405px; position: absolute;/*不定义absolute,js无法设置left和top*/ z-index: -1; } #img li{ width: 720px; height: 405px; float: left; } #index .on{ background-color: black; }
JS part
Image moving function moveElement()
The moveElement function needs to obtain the current position and target position of the picture and calculate the gap between them to move. You can use offsetLeft and offsetTop to obtain the current position of the picture. The effect of "swiping across" the picture when moving is to divide the distance into 10 times for movement, that is, using the setTimeOut function. However, in order to prevent the mouse from hovering, the clearTimeout() function needs to be called. The code is as follows:
function moveElement(ele,x_final,y_final,interval){//ele为元素对象 var x_pos=ele.offsetLeft; var y_pos=ele.offsetTop; var dist=0; if(ele.movement){//防止悬停 clearTimeout(ele.movement); } if(x_pos==x_final&&y_pos==y_final){//先判断是否需要移动 return; } dist=Math.ceil(Math.abs(x_final-x_pos)/10);//分10次移动完成 x_pos = x_pos<x_final ? x_pos+dist : x_pos-dist; dist=Math.ceil(Math.abs(y_final-y_pos)/10);//分10次移动完成 y_pos = y_pos<y_final ? y_pos+dist : y_pos-dist; ele.style.left=x_pos+'px'; ele.style.top=y_pos+'px'; ele.movement=setTimeout(function(){//分10次移动,自调用10次 moveElement(ele,x_final,y_final,interval); },interval) }
Small dot moving function moveIndex()
The essence of moving small dots is to move the background color class set on, the principle is to first determine which li has a background color, remove it if there is one, so that all li have no background, and then add a background to the current li.
function moveIndex(list,num){//移动小圆点 for(var i=0;i<list.length;i++){ if(list[i].className=='on'){//清除li的背景样式 list[i].className=''; } } list[num].className='on'; }
Automatic picture rotation
Write the following code directly in window.onload Just hit it.
Here you need to define a variable index, which means moving to the index (0~n-1, n is the number of li) picture.
var img=document.getElementById('img'); var list=document.getElementById('index').getElementsByTagName('li'); var index=0;//这里定义index是变量,不是属性 var nextMove=function(){//一直向右移动,最后一个之后返回 index+=1; if(index>=list.length){ index=0; } moveIndex(list,index); moveElement(img,-720*index,0,20); };
The automatic carousel of pictures requires the use of the setInterval() function, which allows the program to automatically call the nextMove() function every few seconds:
var play=function(){ timer=setInterval(function(){ nextMove(); },2500); };
The effect of mouse covering small dots
If you want to realize which small dot the mouse covers, the corresponding picture will be displayed For this effect, you need to know which small dot is covered by the mouse. Here, add a custom attribute index to each li so that the value of this attribute is the serial number of the corresponding small dot i (0~n-1, n is the number of li), so that every time the mouse covers it, you only need to get the value of the index attribute to know which small dot the mouse covers. Note that the index attribute has nothing to do with the variable index, they only have the same name.
for(var i=0;i<list.length;i++){//鼠标覆盖上哪个小圆圈,图片就移动到哪个小圆圈,并停止 list[i].index=i;//这里是设置index属性,和index变量没有任何联系 list[i].onmouseover= function () { var clickIndex=parseInt(this.index); moveElement(img,-720*clickIndex,0,20); index=clickIndex; moveIndex(list,index); clearInterval(timer); }; list[i].onmouseout= function () {//移开后继续轮播 play(); }; }
Summary
The movement behavior of the dots is separated, which makes it easier to implement. This carousel picture actually has some problems. When sliding from the last picture to the first picture, the sliding distance is long. In fact, it is easy to solve. Change the sliding method. Here, the final calculation is based on -720*index. The left value, and index is to tie the movement of the picture and the movement of the small dots together. Change the sliding method to the current offsetLeft+ (-720). The movement of the picture can be independent of the index value, and then add a value to the html file. Pictures:
<li><img src="/static/imghwm/default1.png" data-src="../images/img1.jpg" class="lazy" alt="img1"></li> <li><img src="/static/imghwm/default1.png" data-src="../images/img2.jpg" class="lazy" alt="img2"></li> <li><img src="/static/imghwm/default1.png" data-src="../images/img3.jpg" class="lazy" alt="img3"></li> <li><img src="/static/imghwm/default1.png" data-src="../images/img4.jpg" class="lazy" alt="img4"></li> <li><img src="/static/imghwm/default1.png" data-src="../images/img5.jpg" class="lazy" alt="img5"></li> <li><img src="/static/imghwm/default1.png" data-src="../images/img1.jpg" class="lazy" alt="img1"></li>
Then when sliding to the last picture, quickly assign the offset to 0 and change it to the first picture. The two pictures are the same and cannot be Distinguish the changes and achieve seamless connection.
if(x_pos==-3600){ ele.style.left='0'; ele.style.top='0'; }else{ ele.style.left=x_pos+'px'; ele.style.top=y_pos+'px'; }
The above is the detailed content of How to implement sliding carousel images in js?. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

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

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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.

Zend Studio 13.0.1
Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
