Home Web Front-end JS Tutorial How to implement sliding carousel images in js?

How to implement sliding carousel images in js?

Jul 09, 2017 am 09:40 AM
javascript accomplish how

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="../images/img1.jpg" alt="img1"></li>
        <li><img src="../images/img2.jpg" alt="img2"></li>
        <li><img src="../images/img3.jpg" alt="img3"></li>
        <li><img src="../images/img4.jpg" alt="img4"></li>
        <li><img src="../images/img5.jpg" alt="img5"></li>
      </ul>
    </nav>
  <script src="script.js"></script>
  </body>
  </html>
Copy after login

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;
  }
Copy after login

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+&#39;px&#39;;
    ele.style.top=y_pos+&#39;px&#39;;
    
    ele.movement=setTimeout(function(){//分10次移动,自调用10次
      moveElement(ele,x_final,y_final,interval);
    },interval)
  }
Copy after login

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==&#39;on&#39;){//清除li的背景样式
        list[i].className=&#39;&#39;;
      }
    }
    list[num].className=&#39;on&#39;;
  }
Copy after login

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(&#39;img&#39;);
  var list=document.getElementById(&#39;index&#39;).getElementsByTagName(&#39;li&#39;);
  var index=0;//这里定义index是变量,不是属性

  var nextMove=function(){//一直向右移动,最后一个之后返回
    index+=1;
    if(index>=list.length){
      index=0;
    }
    moveIndex(list,index);
    moveElement(img,-720*index,0,20);
  };
Copy after login

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);
  };
Copy after login

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();
    };
  }
Copy after login

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="../images/img1.jpg" alt="img1"></li>
<li><img src="../images/img2.jpg" alt="img2"></li>
<li><img src="../images/img3.jpg" alt="img3"></li>
<li><img src="../images/img4.jpg" alt="img4"></li>
<li><img src="../images/img5.jpg" alt="img5"></li>
<li><img src="../images/img1.jpg" alt="img1"></li>
Copy after login

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=&#39;0&#39;;
    ele.style.top=&#39;0&#39;;
  }else{
    ele.style.left=x_pos+&#39;px&#39;;
    ele.style.top=y_pos+&#39;px&#39;;
  }
Copy after login

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!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

How to implement exact division operation in Golang How to implement exact division operation in Golang Feb 20, 2024 pm 10:51 PM

Implementing exact division operations in Golang is a common need, especially in scenarios involving financial calculations or other scenarios that require high-precision calculations. Golang's built-in division operator "/" is calculated for floating point numbers, and sometimes there is a problem of precision loss. In order to solve this problem, we can use third-party libraries or custom functions to implement exact division operations. A common approach is to use the Rat type from the math/big package, which provides a representation of fractions and can be used to implement exact division operations.

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

PHP Game Requirements Implementation Guide PHP Game Requirements Implementation Guide Mar 11, 2024 am 08:45 AM

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

How to identify genuine and fake shoe boxes of Nike shoes (master one trick to easily identify them) How to identify genuine and fake shoe boxes of Nike shoes (master one trick to easily identify them) Sep 02, 2024 pm 04:11 PM

As a world-renowned sports brand, Nike's shoes have attracted much attention. However, there are also a large number of counterfeit products on the market, including fake Nike shoe boxes. Distinguishing genuine shoe boxes from fake ones is crucial to protecting the rights and interests of consumers. This article will provide you with some simple and effective methods to help you distinguish between real and fake shoe boxes. 1: Outer packaging title By observing the outer packaging of Nike shoe boxes, you can find many subtle differences. Genuine Nike shoe boxes usually have high-quality paper materials that are smooth to the touch and have no obvious pungent smell. The fonts and logos on authentic shoe boxes are usually clear and detailed, and there are no blurs or color inconsistencies. 2: LOGO hot stamping title. The LOGO on Nike shoe boxes is usually hot stamping. The hot stamping part on the genuine shoe box will show

How to view and edit SQL files How to view and edit SQL files Feb 26, 2024 pm 05:12 PM

A SQL file is a text file that usually contains a series of SQL statements. To open a SQL file, you can use a text editor or a specialized SQL development tool. The easiest way to open a SQL file is with a text editor, such as Notepad or Notepad++ in Windows, or Text Editor in Mac. Here are the steps to open a SQL file: First, find the SQL file you want to open, right-click the file, and select "Open with". in the pop-up window

See all articles