search
HomeWeb Front-endJS Tutorialjavascript carousel chart algorithm

javascript carousel chart algorithm

Dec 09, 2016 pm 01:51 PM
javascript

Carousel image is a common image switching effect on the homepage of a website. As a front-end developer, I believe that many developers directly call the encapsulated method in Jquery to implement image carousel, which is trouble-free and simple. So I would like to introduce the image carousel implemented in pure JavaScript code.

HTML

<div id="content_img1">
<ul id="img1">
<li><img  src="/static/imghwm/default1.png"  data-src="img/5.jpg"  class="lazy"  / alt="javascript carousel chart algorithm" ></li>
<li><img  src="/static/imghwm/default1.png"  data-src="img/1.jpg"  class="lazy"  / alt="javascript carousel chart algorithm" ></li>
<li><img  src="/static/imghwm/default1.png"  data-src="img/2.jpg"  class="lazy"  / alt="javascript carousel chart algorithm" ></li>
<li><img  src="/static/imghwm/default1.png"  data-src="img/3.jpg"  class="lazy"  / alt="javascript carousel chart algorithm" ></li>
<li><img  src="/static/imghwm/default1.png"  data-src="img/4.jpg"  class="lazy"  / alt="javascript carousel chart algorithm" ></li>
<li><img  src="/static/imghwm/default1.png"  data-src="img/5.jpg"  class="lazy"  / alt="javascript carousel chart algorithm" ></li>
<li><img  src="/static/imghwm/default1.png"  data-src="img/1.jpg"  class="lazy"  / alt="javascript carousel chart algorithm" ></li>
</ul>
<span class="mouseover" style="margin-left: 300px;">1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
</div>
<div id="content_img2">
<ul id="img2">
<li><img  src="/static/imghwm/default1.png"  data-src="img/5.jpg"  class="lazy"  / alt="javascript carousel chart algorithm" ></li>
<li><img  src="/static/imghwm/default1.png"  data-src="img/1.jpg"  class="lazy"  / alt="javascript carousel chart algorithm" ></li>
<li><img  src="/static/imghwm/default1.png"  data-src="img/2.jpg"  class="lazy"  / alt="javascript carousel chart algorithm" ></li>
<li><img  src="/static/imghwm/default1.png"  data-src="img/3.jpg"  class="lazy"  / alt="javascript carousel chart algorithm" ></li>
<li><img  src="/static/imghwm/default1.png"  data-src="img/4.jpg"  class="lazy"  / alt="javascript carousel chart algorithm" ></li>
<li><img  src="/static/imghwm/default1.png"  data-src="img/5.jpg"  class="lazy"  / alt="javascript carousel chart algorithm" ></li>
<li><img  src="/static/imghwm/default1.png"  data-src="img/1.jpg"  class="lazy"  / alt="javascript carousel chart algorithm" ></li>
</ul>
<span class="mouseover" style="margin-left: 300px;">1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
</div>

I believe the most confusing thing here is, why should two pictures (li) be added at the beginning and end of the five pictures to echo each other? The reason is as shown below:

Here is an example of scrolling to the left as an example


When the layout is started, left: -470px; is first in the second li, which is the second picture, when our pictures continue to scroll to the left When you get to the 7th picture, quickly scroll back to the 2nd picture, and then continue to scroll to the left. This looks like an imaginary infinite left scrolling loop, but in fact it only consists of 7 pictures. Similarly, if we implement right scrolling, when we start the layout, we will first be in the first li, which is the first picture. When our pictures continue to scroll right to the sixth picture, we will quickly pull back to the first picture. picture, then continue scrolling to the right. In fact, the principle of scrolling the carousel up and down is the same, except that there is a float:left attribute missing to allow the li to be arranged vertically.

CSS

*{
margin: 0;
padding: 0;
list-style: none;
}
span{
width: 20px;
height: 20px;
display: block;
background-color: blanchedalmond;
border: 1px solid black;
float: left;
text-align: center;
line-height: 20px;
z-index: 1;
cursor: pointer;
margin: 120px 8px 0 0;
}
span.mouseover{
background-color: orange;
}
#content_img1{
position: relative;
width: 470px;
height: 150px;
border: 2px black solid;
margin: 30px auto;
overflow: hidden;
}
#img1{
position: absolute;
top: 0px;
left: -470px;
z-index: -1;
width: 700%;
height: 150px;
}
#img1>li{
width: 470px;
height: 150px;
float: left;
}
#content_img2{
position: relative;
width: 470px;
height: 150px;
border: 2px black solid;
margin: 30px auto;
overflow: hidden;
}
#img2{
position: absolute;
top: -150px;
left: 0px;
z-index: -1;
width: 470px;
height: 700%;
}
#img2>li{
width: 470px;
height: 150px;
}

javascript function method

window.onload=function(){
var cont_img1=document.getElementById("content_img1");
var spannum1=cont_img1.getElementsByTagName("span");
var img1=document.getElementById("img1");
var cont_img2=document.getElementById("content_img2");
var spannum2=cont_img2.getElementsByTagName("span");
var img2=document.getElementById("img2");
 
   //向左轮播图的span"按钮"鼠标经过事件
 
   for(var i=0;i<spannum1.length;i++){
spannum1[i].index=i;
spannum1[i].onmouseover=function(){
for(var p=0;p<spannum1.length;p++){
if(spannum1[p]==this){
spannum1[p].className="mouseover";
}else{
spannum1[p].className="";
}
}
clearTimeout(img1.timer1);
now=this.index;
scrollimg1(img1,spannum1);
 }
}
 
   //向左轮播的主函数调用
scrollimg1(img1,spannum1);
 
   //向上轮播图的span"按钮"鼠标经过事件
 
for(var i=0;i<spannum2.length;i++){
spannum2[i].index=i;
spannum2[i].onmouseover=function(){
for(var p=0;p<spannum2.length;p++){
if(spannum2[p]==this){
spannum2[p].className="mouseover";
}else{
spannum2[p].className="";
}
}
clearTimeout(img2.timer1);
nows=this.index;
scrollimg2(img2,spannum2);
 }
}
 
    //向上轮播的主函数调用
scrollimg2(img2,spannum2);
 
}
 
   var now=1;
 function scrollimg1(obj,spannum1){
 if(obj.offsetLeft<=-(obj.children.length-1)*obj.children[0].offsetWidth){//达到极限的计算位置,既是最后一个图就马上扯回初始位置
 now=0;
 obj.style.left=-(++now)*obj.children[0].offsetWidth+"px";
 }else{
 Move(obj,-obj.children[0].offsetWidth*(++now),"left",5,30);//否则图片进行向左运动的缓冲动画
 }
 for(var i=0;i<spannum1.length;i++){
  
spannum1[i].className="";
 }
 spannum1[(now-1)%spannum1.length].className="mouseover";
 obj.timer1=setTimeout(function(){//每3秒钟进行函数的回调,实现无限循环的图片轮播
  
scrollimg1(obj,spannum1);
 },3000);
 }
  
 var nows=1;
 function scrollimg2(obj,spannum2){
 if(obj.offsetTop<=-(obj.children.length-1)*obj.children[0].offsetHeight){//达到极限的计算位置,既是最后一个图就马上扯回初始位置
 nows=0;
 obj.style.top=-(++nows)*obj.children[0].offsetHeight+"px";
 }else{
 Move(obj,-obj.children[0].offsetHeight*(++nows),"top",5,30);//否则图片进行向左运动的缓冲动画
 }
 for(var i=0;i<spannum2.length;i++){
  
spannum2[i].className="";
 }
 spannum2[(nows-1)%spannum2.length].className="mouseover";
 obj.timer1=setTimeout(function(){//每3秒钟进行函数的回调,实现无限循环的图片轮播
  
scrollimg2(obj,spannum2);
 },3000);
 }
 
 
 
function Move(obj,target,stylename,average,cycle,continuefunction){参数类型:(对象,目标值,改变的样式属性,缓冲系数(速度与大小成反比),周期时间(速度与大小成反比),回调函数(可有可无))
 clearInterval(obj.timer);
 obj.timer=setInterval(function(){
if(stylename=="opacity"){
var offvalue=Math.round(parseFloat(getStyle(obj,stylename))*100);
var speed=(target-offvalue)/average;
 speed=speed>0?Math.ceil(speed):Math.floor(speed);
 if(speed==0){
clearInterval(obj.timer);
if(continuefunction) continuefunction();
 }else{
obj.style[stylename]=(offvalue+speed)/100;
obj.style.filter="alpha(opacity:"+(offvalue+speed)+")";
 }
}else{
var offvalue=parseInt(getStyle(obj,stylename));
var speed=(target-offvalue)/average;
 speed=speed>0?Math.ceil(speed):Math.floor(speed);
 if(speed==0){
clearInterval(obj.timer);
if(continuefunction) continuefunction();
 }else{
obj.style[stylename]=offvalue+speed+"px";
 }
}
},cycle);
}
function getStyle(obj,stylename){//对象样式属性大小获取函数
if(obj.currentStyle){
return obj.currentStyle[stylename];
}else if(getComputedStyle(obj,false)){
return getComputedStyle(obj,false)[stylename];
}
}

The advantage of this carousel algorithm by calculating the position is that it can be within the scope of my style, in the

    Add unlimited pictures in li, but remember to add matching li pictures at the beginning and end, and change the style according to the size of the picture to achieve picture carousel.


    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

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code 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.

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.