


Teach you step by step to write a fade-in and fade-out picture carousel plug-in with annotations (2)_javascript skills
Continuing from the previous article, now comes the second part.
Before we start, let’s talk about the optimization problem mentioned above about writing all functions in a closure. As mentioned before, because we only need to call init during initialization, we can only write init into the closure, and other functional functions can be called as the prototype inheritance method of init. So the previous code can actually be rewritten like this:
var Hongru= {};
function H$(id){return document.getElementById(id)}
function H$$(c,p){return p.getElementsByTagName(c)}
Hongru.fader = function (){
function init(options){ //options parameters: id (required): picture list parent tag id; auto (optional): automatic running time; index (optional): starting running picture Serial number
var wp = H$(options.id), // Get the parent element of the picture list
ul = H$$('ul',wp)[0], // Get
li = this .li = H$$('li',ul);
this.a = options.auto?options.auto:2; //Automatic running interval
this.index = options.position?options.position :0; //The picture serial number to start running (starting from 0)
this.l = li.length;
this.cur = this.z = 0; //The currently displayed picture serial number&&z-index variable
this.pos(this.index); //Transformation function
}
init.prototype = {
auto:function(){
this.li.a = setInterval(new Function ('Hongru.fader.move(1)'),this.a*1000);
},
move:function(i){//There are two options for parameter i, 1 and -1,1 It means running to the next one, -1 means running to the previous one
var n = this.cur i;
var m = i==1?n==this.l?0:n:nthis.pos(m); //Convert to the previous or next card Zhang
},
pos:function(i){
clearInterval(this.li.a);
this.z;
this.li[i].style.zIndex = this .z; //Increase the z-index of the next picture by one each time
this.cur = i; //Bind the correct serial number of the currently displayed picture
this.auto(); //Automatically run
}
}
return {init:init}
}();
But this is actually problematic. I don’t know if you will find it if it is rewritten like this. , you can no longer call 'Hongru.fader.move()' in the auto function. This is undefined. Then some people will say that since it is the prototype inheritance of init, then call 'Hongru.fader.init.move() )'Isn't that right? In fact, that's not right. I have discussed this issue in my previous article http://www.cnblogs.com/hongru/archive/2010/10/09/1846636.html; init cannot access it before it is instantiated. prototype, so we need to pay attention to two issues when doing this.
One is to use the new keyword to instantiate init during initialization.
The other is that when calling its prototype method inside the code, it must also be called through the object we instantiated. For example, when we initialize the above code, it should be like this
var newFader = new Hongru.fader.init({ //This new is very important
id:'fader'
});
If we want to call the init method in the code, we need to call it through our new instantiation object newFader, such as the auto function above If you want to call the init's move method, just call 'newFader.move()' directly. This will work.
But there is a small problem, that is, the instantiated variable name must be consistent with the name called in the code. So if I change the name of my initialization object, such as using newFader1, then I have to change the source code. This is definitely not possible, so a little trick is to pass one more parameter in init, make the variable name consistent with the parameter when initializing, and then call it through the parameter in the source code. In this way, the problem is successfully solved.
(ps: The reason why new Function is used in the code is also because it can break the scope chain, which is also one of the conditions to ensure that we can structure our code in this way.)
In summary: the previous code should be like this Optimization:
var Hongru={};
function H$(id){return document.getElementById(id)}
function H$$(c,p){return p.getElementsByTagName(c) }
Hongru.fader = function(){
function init(anthor,options){this.anthor=anthor; this.init(options);}
init.prototype = {
init: function(options){ //options parameters: id (required): picture list parent tag id; auto (optional): automatic running time; index (optional): starting picture serial number
var wp = H$(options.id), // Get the parent element of the picture list
ul = H$$('ul',wp)[0], // Get
li = this.li = H$$( 'li',ul);
this.a = options.auto?options.auto:2; //Automatic running interval
this.index = options.position?options.position:0; //Start running The picture serial number (starting from 0)
this.l = li.length;
this.cur = this.z = 0; //The currently displayed picture serial number&&z-index variable
this.pos( this.index); //Transformation function
},
auto:function(){
this.li.a = setInterval(new Function(this.anthor '.move(1)'),this .a*1000);
},
move:function(i){//There are two options for parameter i, 1 and -1, 1 means running to the next one, and -1 means running to the previous one. Zhang
var n = this.cur i;
var m = i==1?n==this.l?0:n:nthis.pos(m); //Convert to the previous or next picture
},
pos:function(i ){
clearInterval(this.li.a);
this.z;
this.li[i].style.zIndex = this.z; //Let the next picture z- each time index plus one
this.cur = i; //Bind the correct serial number of the currently displayed image
this.auto(); //Automatically run
}
}
return {init: init}
}();
It should be initialized like this:
var fader = new Hongru.fader.init('fader',{ //Make sure the first parameter is consistent with the variable name
id:'fader'
}) ;
Okay, the code optimization plan ends here. The following is the implementation of the second part of the effect: Fade in and fade out effect
In fact, with the good code structure and logic above, it is relatively easy to add the fade in and fade out effect. The idea is very simple. Make the picture transparent before changing, and then pass Timer to gradually increase transparency. But there are several boundary judgments that are more important. At the same time, when changing transparency in IE and non-IE, you should pay attention to using different css attributes.
The changes to the core code are the following two paragraphs. One is to add the transparency gradient function fade(), and the other is to make the image transparent first in pos() --> and then start executing fade()
Add a code segment in pos():
if(this .li[i].o>=100){ //Set the image transparency to transparent before fading in
this.li[i].o = 0;
this.li[i].style .opacity = 0;
this.li[i].style.filter = 'alpha(opacity=0)';
}
this.li[i].f = setInterval(new Function(this .anthor '.fade(' i ')'),20);
Then add a function fade()
fade:function(i){
if(this.li[i].o>=100){
clearInterval (this.li[i].f); //If the transparency change is completed, clear the timer
if(!this.li.a){ //Make sure all timers are cleared before starting automatic operation. Otherwise, if the controller is clicked too fast, the timer will start the next change before it has time to clear, and the function will be messed up
this.auto();
}
}
else{ //Transparency changes
this.li[i].o =5;
this.li[i].style.opacity = this.li[i].o/100;
this.li[ i].style.filter = 'alpha(opacity=' this.li[i].o ')';
}
}
Okay, it's that simple. But another thing to remember is that you must remember to clear the last timer at the beginning of the pos() call! !
Post the entire source code below:
var Hongru={};
function H$(id){return document.getElementById(id)}
function H$$(c,p){return p.getElementsByTagName(c) }
Hongru.fader = function(){
function init(anthor,options){this.anthor=anthor; this.init(options);}
init.prototype = {
init: function(options){ //options parameters: id (required): picture list parent tag id; auto (optional): automatic running time; index (optional): starting picture serial number
var wp = H$(options.id), // Get the parent element of the picture list
ul = H$$('ul',wp)[0], // Get
li = this.li = H$$( 'li',ul);
this.a = options.auto?options.auto:2; //Automatic running interval
this.index = options.position?options.position:0; //Start running Picture serial number (starting from 0)
this.l = li.length;
this.cur = this.z = 0; //Currently displayed picture serial number&&z-index variable
/* == Add fade-in and fade-out function ==*/
for(var i=0;i
this.li[i].style.opacity = this.li[i].o/100; //For non-IE, just use opacity
this.li[i].style.filter = 'alpha(opacity=' this.li[i].o ')'; //IE filter
}
this.pos(this.index); //Transformation function
},
auto:function(){
this.li.a = setInterval(new Function(this.anthor '.move(1)'),this.a*1000);
},
move :function(i){//There are two options for parameter i, 1 and -1, 1 means running to the next picture, -1 means running to the previous picture
var n = this.cur i;
var m = i==1?n==this.l?0:n:nthis.pos(m); //Transform to the previous or next picture
},
pos:function(i){
clearInterval(this.li.a); / /Clear the automatic change timer
clearInterval(this.li[i].f); //Clear the fade effect timer
this.z;
this.li[i].style.zIndex = this.z; //Increase the z-index of the next picture by one each time
this.cur = i; //Bind the correct serial number of the currently displayed picture
this.li.a = false; // Make a mark, which will be used below, indicating that the clear timer has been completed
//this.auto(); //Automatically run
if(this.li[i].o>=100){ // Before the image fades in, set the image transparency to transparent
this.li[i].o = 0;
this.li[i].style.opacity = 0;
this.li[i] .style.filter = 'alpha(opacity=0)';
}
this.li[i].f = setInterval(new Function(this.anthor '.fade(' i ')'),20 );
},
fade:function(i){
if(this.li[i].o>=100){
clearInterval(this.li[i].f); //If the transparency change is completed, clear the timer
if(!this.li.a){ //Make sure all timers are cleared before starting automatic operation. Otherwise, if the controller is clicked too fast, the timer will start the next change before it has time to clear, and the function will be messed up
this.auto();
}
}
else{
this.li[i].o =5;
this.li[i].style.opacity = this.li[i].o/100;
this.li[i].style .filter = 'alpha(opacity=' this.li[i].o ')';
}
}
}
return {init:init}
}();
Everyone should pay attention to the notes I wrote. Some places are more critical.
Let’s take a look at the running effect:
If you need to introduce external Js, you need to refresh to execute ]
Some people may have noticed that the fade in and fade out here is just a title. In fact, it only has a fade in effect, but it doesn’t matter. The effect is basically the same as a fade out, and even if you want to fade out, you only need to change two sentences. Haha
This part ends here, the next part will add the controller.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

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 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.

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.

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.

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.

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


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool