search
HomeWeb Front-endJS Tutorialjquery implements carousel chart (with code)

This time I will bring you jquery to implement carousel chart (with code). What are the precautions for jquery to implement carousel chart? The following is a practical case, let’s take a look.

Carousel chart:

I have been exposed to jquery for a while, and today I just used the carousel chart to practice my skills. At the beginning of the blog post, I will introduce an example of simply using jquery to make a carousel chart. In the middle, I will insert some more thoughts about carousel charts. At the end, I will use Javascript method to write a carousel chart. Finally, I will talk about jquery and Javascript. Comparison. The effect of the carousel chart can be viewed by clicking on the following link: http://sandbox.runjs.cn/show/t07kscph

Example of jquery making carousel chart:

HTML part code:

nbsp;html>

  
    <meta>
    <title>轮播图</title>
    <link>
    <script></script>
    <script></script>
  
  
    <p>
      <a><img  src="/static/imghwm/default1.png" data-src="images/1.jpg" class="lazy" alt="jquery implements carousel chart (with code)" ></a>
      <a><img  src="/static/imghwm/default1.png" data-src="images/2.jpg" class="lazy" alt="jquery implements carousel chart (with code)" ></a>
      <a><img  src="/static/imghwm/default1.png" data-src="images/3.jpg" class="lazy" alt="jquery implements carousel chart (with code)" ></a>
      <a><img  src="/static/imghwm/default1.png" data-src="images/4.jpg" class="lazy" alt="jquery implements carousel chart (with code)" ></a>
      <a><img  src="/static/imghwm/default1.png" data-src="images/5.jpg" class="lazy" alt="jquery implements carousel chart (with code)" ></a>
      
      </p><p>
      </p><p>></p>
      
      
            
  • 1
  •         
  • 2
  •         
  • 3
  •         
  • 4
  •         
  • 5
  •       
       

css part code:

* {
  margin: 0;
  padding: 0;
}
#igs {
  margin: 10px auto;
  width: 700px;
  height: 320px;
  position: relative;
}
.ig {
  position: absolute;
}
#tabs {
  position: absolute;
  list-style: none;
  background-color: rgba(255,255,255,.5);
  left: 300px;
  bottom: 10px;
  border-radius: 10px;
  padding: 5px 0 5px 5px;
}
.tab{
  float: left;
  text-align: center;
  line-height: 20px;
  width: 20px;
  height: 20px;
  cursor: pointer;
  overflow: hidden;
  margin-right: 4px;
  border-radius: 100%;
  background-color: rgb(200,100,150);
}
.btn{
  position: absolute;
  color: #fff;
  top: 110px;
  width: 40px;
  height: 100px;
  background-color: rgba(255,255,255,.3);
  font-size: 40px;
  font-weight: bold;
  text-align: center;
  line-height: 100px;
  border-radius: 5px;
  margin: 0 5px;
}
.btn2{
  position: absolute;
  right: 0px;
}
.btn:hover{
  background-color: rgba(0,0,0,.7);
}

js part code:

//定义全局变量和定时器
var i = 0 ;
var timer;
$(document).ready(function(){
  //用jquery方法设置第一张图片显示,其余隐藏
  $('.ig').eq(0).show().siblings('.ig').hide();
  
  //调用showTime()函数(轮播函数)
  showTime();
  
  //当鼠标经过下面的数字时,触发两个事件(鼠标悬停和鼠标离开)
  $('.tab').hover(function(){
    //获取当前i的值,并显示,同时还要清除定时器
    i = $(this).index();
    Show();
    clearInterval(timer);
  },function(){
    //
    showTime();
  });
  
  //鼠标点击左侧的箭头
  $('.btn1').click(function(){
    clearInterval(timer);
    if(i == 0){
      i = 5;//注意此时i的值
    }
    i--;
    Show();
    showTime();
  });
  
  //鼠标点击右侧的箭头
  $('.btn2').click(function(){
    clearInterval(timer);
    if(i == 4){
      i = -1;//注意此时i的值
    }
    i++;
    Show();
    showTime();
  });
  
});
//创建一个showTime函数
function showTime(){
  //定时器
  timer = setInterval(function(){
    //调用一个Show()函数
    Show();
    i++;
    //当图片是最后一张的后面时,设置图片为第一张
    if(i==5){
      i=0;
    }
  },2000);
}
//创建一个Show函数
function Show(){
  //在这里可以用其他jquery的动画
  $('.ig').eq(i).fadeIn(300).siblings('.ig').fadeOut(300);
  
  //给.tab创建一个新的Class为其添加一个新的样式,并且要在css代码中设置该样式
  $('.tab').eq(i).addClass('bg').siblings('.tab').removeClass('bg');
  
  /*
   * css中添加的代码:
   * .bg{ background-color: #f00; }
   * */
}

Completed rendering:

More thoughts on jquery for making carousel pictures

Thought 1: Use the jquery method in the seventh line of code to set the first picture to be displayed and the rest to be hidden. Is there any other way to achieve this?

Idea: Implement it through jquery filters

Code example:

$("#igs a:not(
:first-child
)").hide();

Extension: If you look at it this way, in the a tag We can omit all the classes in. At the same time, we need to have a deeper understanding of jquery selectors.

Thinking 2: In line 64 of the code, we created a Show function, where we can only see simple effects. Can we make our animation effects more dazzling?

Idea: Use custom animation in jquery to set multiple animation effects

Code example:

//Code tip: You can use fadeIn(), fadeOut (), fadeTo(), animate(), etc. Please refer to relevant information for specific implementation methods

Thinking 3: If we add one or more pictures on the original basis, we have to modify our Code, can we apply this code to more carousel images?

Idea: We set a counter count in front and get the number of pictures through the DOM method

Code example:

var count;
$(document).ready(function(){
  count= $(".main a").length; /*给动态变化的i备用*/;
  //。。。代码省略
  
  //鼠标点击左侧的箭头
  $('.btn1').click(function(){
    clearInterval(timer);
    if(i == 0){
      i = count;//注意此时i的值
    }
    i--;
    Show();
    showTime();
  });
  
  //鼠标点击右侧的箭头
  $('.btn2').click(function(){
    clearInterval(timer);
    //console.log(count-1);
    if(i == count-1){
      i = -1;//注意此时i的值
    }
    i++;
    Show();
    showTime();
  });
  
});

Use native Javascript method to write a simple wheel Play the picture

Part of the html code:

<p>
  </p><p>
    <img  src="/static/imghwm/default1.png" data-src="img/5.jpg" class="lazy" alt="jquery implements carousel chart (with code)" >
    <img  src="/static/imghwm/default1.png" data-src="img/1.jpg" class="lazy" alt="jquery implements carousel chart (with code)" >
    <img  src="/static/imghwm/default1.png" data-src="img/2.jpg" class="lazy" alt="jquery implements carousel chart (with code)" >
    <img  src="/static/imghwm/default1.png" data-src="img/3.jpg" class="lazy" alt="jquery implements carousel chart (with code)" >
    <img  src="/static/imghwm/default1.png" data-src="img/4.jpg" class="lazy" alt="jquery implements carousel chart (with code)" >
    <img  src="/static/imghwm/default1.png" data-src="img/5.jpg" class="lazy" alt="jquery implements carousel chart (with code)" >
    <img  src="/static/imghwm/default1.png" data-src="img/1.jpg" class="lazy" alt="jquery implements carousel chart (with code)" >
  </p>
  <p>
    <span></span>
    <span></span>
    <span></span>
    <span></span>
    <span></span>
  </p>
  <a>
  </a><a>></a>

Js part of the code:

<script>
    /* 知识点:    */
    /*    this用法 */
    /*    DOM事件 */
    /*    定时器 */
    window.onload = function () {
      var container = document.getElementById(&#39;container&#39;);
      var list = document.getElementById(&#39;list&#39;);
      var buttons = document.getElementById(&#39;buttons&#39;).getElementsByTagName(&#39;span&#39;);
      var prev = document.getElementById(&#39;prev&#39;);
      var next = document.getElementById(&#39;next&#39;);
      var index = 1;
      var timer;
      function animate(offset) {
        //获取的是style.left,是相对左边获取距离,所以第一张图后style.left都为负值,
        //且style.left获取的是字符串,需要用parseInt()取整转化为数字。
        var newLeft = parseInt(list.style.left) + offset;
        list.style.left = newLeft + &#39;px&#39;;
        //无限滚动判断
        if (newLeft > -600) {
          list.style.left = -3000 + &#39;px&#39;;
        }
        if (newLeft < -3000) {
          list.style.left = -600 + &#39;px&#39;;
        }
      }
      function play() {
        //重复执行的定时器
        timer = setInterval(function () {
          next.onclick();
        }, 2000)
      }
      function stop() {
        clearInterval(timer);
      }
      function buttonsShow() {
        //将之前的小圆点的样式清除
        for (var i = 0; i < buttons.length; i++) {
          if (buttons[i].className == "on") {
            buttons[i].className = "";
          }
        }
        //数组从0开始,故index需要-1
        buttons[index - 1].className = "on";
      }
      prev.onclick = function () {
        index -= 1;
        if (index < 1) {
          index = 5
        }
        buttonsShow();
        animate(600);
      };
      next.onclick = function () {
        //由于上边定时器的作用,index会一直递增下去,我们只有5个小圆点,所以需要做出判断
        index += 1;
        if (index > 5) {
          index = 1
        }
        animate(-600);
        buttonsShow();
      };
      for (var i = 0; i < buttons.length; i++) {
        (function (i) {
          buttons[i].onclick = function () {
            /* 这里获得鼠标移动到小圆点的位置,用this把index绑定到对象buttons[i]上,去谷歌this的用法 */
            /* 由于这里的index是自定义属性,需要用到getAttribute()这个DOM2级方法,去获取自定义index的属性*/
            var clickIndex = parseInt(this.getAttribute(&#39;index&#39;));
            var offset = 600 * (index - clickIndex); //这个index是当前图片停留时的index
            animate(offset);
            index = clickIndex; //存放鼠标点击后的位置,用于小圆点的正常显示
            buttonsShow();
          }
        })(i)
      }
      container.onmouseover = stop;
      container.onmouseout = play;
      play();
    }
  </script>

Comparison of jquery and Javascript methods

After comparison , we can easily see that the jquery method requires much less code than our Javascript method. In fact, using Javascript directly avoids many problems, such as compatibility issues (this example is not tested, just used for comparison); also, if there are two values ​​of class, separated by spaces, then How should we operate with DOM (idea: use regular expression and array-related methods), so that our code amount will be more; if we want to change the animation effect, we need to modify a lot. , and from the previous introduction, we know that if you want to modify the animation effect, just modify the called animation function directly...

The following words:

This blog post records more of my thinking, among which The specific implementation effects of many methods have not yet been written. Now I am learning jquery while reviewing the Javascript I have learned before. I feel more and more that Javascript is powerful (actually I am weak). There are many things worth studying in depth, and I feel more and more interesting about this thing.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

What are the precautions for jQuery version upgrade

Use of $. and $(). in jQuery Detailed explanation

The above is the detailed content of jquery implements carousel chart (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
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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.

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor