search
HomeWeb Front-endJS TutorialSharing api style code as easy to use as jQuery_javascript skills

Back to the topic, an API style as easy to use as jQuery? So what kind of style is it? There are two points that I personally think are more important. One is the chained calls to DOM operations, which are all in a queue state. This not only makes the readable semantics of the code easy to understand, but also eliminates the need for multiple calls to the same DOM element. It is very important to embed callbacks in callbacks during chain operations.
The second is batch operation of elements, which is based on its powerful selector. The jq selector is very powerful, as everyone knows, so I won’t say more. And it certainly can’t be achieved in a day or two, so let’s talk about my views on the two points I mentioned.

Based on its powerful selector, all jquery DOM operations rely on an array obtained based on its selector. Many people like to call this a jq object. So let’s call it that for now. Then all DOM operations rely on each element in this jq object to be executed concurrently and in batches. Specific to each DOM operation, most of them are in the state of chained callbacks. That is to say, in this method chain, the order of their execution can be known directly based on the order of method calls in the chain. This method chain and serial form is a major feature of it.
So many people like to use jquery because they basically like it for two reasons. The selector is really powerful, the chain call is really convenient and easy to use, and the code logic becomes simple instantly. Precisely because it handles a lot of code logic internally, there are fewer issues left for coders to consider. So while you find it useful, you also lose an opportunity to practice coding logic. Therefore, I do not recommend that beginners learn to use jquery or other frameworks directly, because they will make you understand js less and less. My point of view is that all frameworks or libraries are used to improve development efficiency and management convenience, not to learn. (Of course, except those who study the source code).
So, since we think jquery’s API style is easy to use, why don’t we try to build this similar API style? (Disclaimer: The following attempts are only to provide an idea, the code is not perfect...)

Copy code The code is as follows:

var get = function (ids) {
var d = document, a = -1;
this.elements = [];
if (typeof ids != ' string' && !!ids.length) {
for (var i=0; ivar id = ids[i], o;
o = typeof id = = 'string' ? d.getElementById(id) : id;
this.elements.push(o);
}
} else {
while (typeof arguments[ a] == 'string ') {
this.elements.push(d.getElementById(arguments[a]));
}
}
}

Then extend some operations for it DOM method
Copy code The code is as follows:

get.prototype = {
each : function () {},
animate : function () {}
}

Of course, this method looks different from jQuery, but you can understand it, jquery is possible It looks like this:
Copy the code The code is as follows:

jQuery = window.jQuery = window. $ = function( selector, context ) {

return new jQuery.fn.init( selector, context );
}

jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {}
}

Next, batch operations on the acquired queues inevitably require an each traversal method.
Copy code The code is as follows:

each : function (fn) {
for ( var i=0; ifn.call(this, this.elements[i])
}
return this;
},

Each is a method extended by get.prototype, providing a parameter function, traversing the dom list, and binding the function to each element. Then let it return get.prototype, because the prototype itself has properties similar to a "superclass", so any method returned to the prototype object can continue to call the prototype extension method.

In order to make this attempt more meaningful, let’s make an animate function next. This function is a very common method for JQuery to operate DOM. With it, most animations have become so simple and easy. The following will be a simple implementation:
Copy the code The code is as follows:

animate: function (config) {
if (!this.animQueue) this.animQueue = HR._animQueue = [];
var a = 0, time, tween, ease, callback;
while (arguments[ a]) {
if (typeof arguments[a] == 'number') time = arguments[a];
if (typeof arguments[a] == 'string') {
if (/^ease*/.test(arguments[a])) ease = arguments[a];
else tween = arguments[a];
}
if (HR.isFunction (arguments[a])) callback = arguments[a];
}

this.animQueue.push({
config: config,
time: time,
tween: tween,
ease: ease,
callback: callback
});
if (this.animQueue.length == 1) this.execute(this.animQueue);

return this;
},

You may not see any clues just by looking at this paragraph. Yes, because to make a serial method chain like jquery, a temporary queue is needed. Operation, otherwise even if the method chain is formed, these methods will be parallel and cannot achieve the effect we want. So the above piece of code mainly handles the logic of pushing animate into the queue, and then makes some judgments on the parameter arguments so that you can be more casual when writing parameters. Except for the first parameter and the last callback, the other parameters do not need to consider the position. and required to enhance ease of use.
The core transformation function is on execute,
Copy code The code is as follows:

execute : function (queue) {
var _this = this, m = 0, n = 0,
_anim = function (el, key, from, to, at, tw, ease, cb) {
var isOP = (key == 'opacity' && !HR.support.opacity), _key = key;
if (isOP) {to = to*100; _key = 'filter'}
var s = new Date ,
d = at,
b = parseFloat(from) || 0,
c = to-b;

(function () {
var t = new Date - s;
if (t >= d) {
n ;
t = d;
el.style[_key] = (isOP ? 'alpha(opacity=' : '') Tween .Linear(t, b, c, d) (key != 'opacity' ? 'px' : '') (isOP ? ')' : '');
!!cb && cb.apply(el) ;
if (m == n && _this.animQueue.length > 1) {
_this.animQueue.shift();
_this.execute(_this.animQueue);
}

return;
}
el.style[_key] = (isOP ? 'alpha(opacity=' : '') Tween[tw][ease](t, b, c, d) ( key != 'opacity' ? 'px' : '') (isOP ? ')' : '');

if (!HR.timers[el.id]) HR.timers[el.id ] = [];
HR.timers[el.id].push(setTimeout(arguments.callee, 16));

})();
},
_q = this.animQueue[0];

return this.each(function (el) {
for (var k in _q.config) {
m ;
_anim(el,
k,
k == 'opacity' && !HR.support.opacity ? HR.getStyle('filter', el) == '' ? 100 : parseInt(HR.getStyle('filter', el). match(/d{1,3}/g)[0]) : HR.getStyle(k, el),
_q.config[k],
typeof _q.time == 'number' ? _q .time : 1000,
typeof _q.tween == 'string' && !/^ease*/.test(_q.tween) ? _q.tween : 'Quart',
typeof _q.ease == ' string' && /^ease*/.test(_q.ease) ? _q.ease : 'easeOut',
_q.callback)
}
});
}

This section seems a little more complicated. The most basic change is still in the private function _anim. The rest of the code is basically doing some batch operations, compatibility with transparency changes, and whether the current transformation has been completed. Combining these two paragraphs, the effect of jquery's animate is basically achieved. Belongs to a simplified version.
Of course, we must not forget a very important point, that is, since it can be transformed, there must be a stop method to make the transformation controllable, otherwise the usability of this code will be greatly reduced. Please refer to the following code:
Copy code The code is as follows:

stop: function (clearQueue) {
if (clearQueue) HR ._animQueue.length = 0;
this.each(function (el) {
if (!!HR.timers[el.id])
for (var i=0; i});
return this;
},

Set up special temporary timer storage for different dom element IDs, HR.timers[el.id], then traverse the current dom list and clear the corresponding timers. The parameter clearQueue is an optional parameter, used to control whether to clear subsequent animates waiting for execution.

In order to make this method more fun, I added several additional easing methods. jquery only has one kind of swing, and then all the easing algorithms are placed in the Tween object for use. The following is the source code I used for testing, (please forgive me if there are any mistakes)
Copy the code The code is as follows:

/* =========== animate js ============ */
/* @author:hongru.chen */
/* =================================== */

if (typeof HR == 'undefined' || !HR)
HR = {
extend : function (destination, source, override) {
if (override === #ff0000) override = true;
for (var property in source) {
if (override || !(property in destination)) {
destination[property] = source[property];
}
}
return destination;
}
};

(function () {

var Tween = { // The parameters of the following operators are represented respectively: t: running time, b: starting amount, c: total change, d: total time
Linear: function(t,b,c,d){ return c*t/d b; },
Quad: {
easeIn: function(t, b,c,d){
return c*(t/=d)*t b;
},
easeOut: function(t,b,c,d){
return -c * (t/=d)*(t-2) b;
},
easeInOut: function(t,b,c,d){
if ((t/=d/2) return -c/2 * ((--t)*(t-2) - 1) b;
}
},
Cubic : {
easeIn: function(t,b,c,d){
return c*(t/=d)*t*t b;
},
easeOut: function(t,b ,c,d){
return c*((t=t/d-1)*t*t 1) b;
},
easeInOut: function(t,b,c,d) {
if ((t/=d/2) return c/2*((t-=2)*t*t 2) b;
}
},
Quart: {
easeIn: function(t,b,c,d){
return c*(t/=d)*t*t* t b;
},
easeOut: function(t,b,c,d){
return -c * ((t=t/d-1)*t*t*t - 1) b ;
},
easeInOut: function(t,b,c,d){
if ((t/=d/2) return -c/2 * ((t-=2)*t*t*t - 2) b;
}
},
Quint: {
easeIn: function (t,b,c,d){
return c*(t/=d)*t*t*t*t b;
},
easeOut: function(t,b,c,d ){
return c*((t=t/d-1)*t*t*t*t 1) b;
},
easeInOut: function(t,b,c,d) {
if ((t/=d/2) return c/2*((t-=2)*t *t*t*t 2) b;
}
},
Sine: {
easeIn: function(t,b,c,d){
return -c * Math. cos(t/d * (Math.PI/2)) c b;
},
easeOut: function(t,b,c,d){
return c * Math.sin(t/d * (Math.PI/2)) b;
},
easeInOut: function(t,b,c,d){
return -c/2 * (Math.cos(Math.PI* t/d) - 1) b;
}
},
Expo: {
easeIn: function(t,b,c,d){
return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) b;
},
easeOut: function(t,b,c,d){
return (t ==d) ? b c : c * (-Math.pow(2, -10 * t/d) 1) b;
},
easeInOut: function(t,b,c,d){
if (t==0) return b;
if (t==d) return b c;
if ((t/=d/2) return c/2 * (-Math.pow(2, -10 * --t) 2) b;
}
},
Circ: {
easeIn: function(t,b,c,d){
return -c * (Math.sqrt(1 - (t/=d)*t) - 1) b;
},
easeOut: function(t,b,c,d){
return c * Math.sqrt(1 - (t=t/d-1)*t) b;
} ,
easeInOut: function(t,b,c,d){
if ((t/=d/2) return c/2 * (Math.sqrt(1 - (t-=2)*t) 1) b;
}
},
Elastic: {
easeIn: function(t,b,c,d,a,p){
if (t==0) return b; if ((t/=d)==1) return b c; if (! p) p=d*.3;
if (!a || a else var s = p/ (2*Math.PI) * Math.asin (c/a);
return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s) *(2*Math.PI)/p )) b;
},
easeOut: function(t,b,c,d,a,p){
if (t==0) return b; if ((t/=d)==1) return b c; if (!p) p=d*.3;
if (!a || a else var s = p/(2*Math.PI) * Math.asin (c/a);
return (a*Math.pow(2, -10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) c b);
},
easeInOut: function(t,b,c,d,a ,p){
if (t==0) return b; if ((t/=d/2)==2) return b c; if (!p) p=d*(.3*1.5);
if (!a || a else var s = p/(2*Math.PI) * Math .asin (c/a);
if (t return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2 *Math.PI)/p )*.5 c b;
}
},
Back: {
easeIn: function(t,b,c,d,s){
if (s == undefined) s = 1.70158;
return c*(t/=d)*t*((s 1)*t - s) b;
},
easeOut: function(t ,b,c,d,s){
if (s == undefined) s = 1.70158;
return c*((t=t/d-1)*t*((s 1)*t s ) 1) b;
},
easeInOut: function(t,b,c,d,s){
if (s == undefined) s = 1.70158;
if ((t/ =d/2) return c/2*((t -=2)*t*(((s*=(1.525)) 1)*t s) 2) b;
}
},
Bounce: {
easeIn: function(t, b,c,d){
return c - Tween.Bounce.easeOut(d-t, 0, c, d) b;
},
easeOut: function(t,b,c,d){
if ((t/=d) return c*(7.5625*t*t) b;
} else if (t return c*(7.5625*(t-=(1.5/2.75))*t .75) b;
} else if (t return c *(7.5625*(t-=(2.25/2.75))*t .9375) b;
} else {
return c*(7.5625*(t-=(2.625/2.75))*t .984375 ) b;
}
},
easeInOut: function(t,b,c,d){
if (t else return Tween.Bounce.easeOut(t*2-d, 0, c, d) * .5 c*.5 b;
}
}
}

var get = function (ids) {
var d = document, a = -1;
this.elements = [];
if (typeof ids != 'string' && !!ids.length) {
for (var i=0; ivar id = ids[i], o;
o = typeof id == 'string' ? d.getElementById(id) : id;
this.elements.push(o);
}
} else {
while (typeof arguments[ a] == 'string') {
this.elements.push(d.getElementById(arguments[a]));
}
}
}

get.prototype = {

each : function (fn) {
for (var i=0; ifn.call(this, this.elements[i])
}
return this;
},

setStyle : function (p, v) {
this.each(function (el) {
el.style[p] = v;
});
return this;
},

show : function () {
var _this = this;
this.each(function (el) {
_this.setStyle('display', 'block');
})
return this;
},

hide : function () {
var _this = this;
this.each(function (el) {
_this.setStyle('display', 'none');
})
return this;
},

animate: function (config) {
if (!this.animQueue) this.animQueue = HR._animQueue = [];
var a = 0, time, tween, ease, callback;
while (arguments[ a]) {
if (typeof arguments[a] == 'number') time = arguments[a];
if (typeof arguments[a] == 'string') {
if (/^ease*/.test(arguments[a])) ease = arguments[a];
else tween = arguments[a];
}
if (HR.isFunction(arguments[a])) callback = arguments[a];
}

this.animQueue.push({
config: config,
time: time,
tween: tween,
ease: ease,
callback: callback
});
if (this.animQueue.length == 1) this.execute(this.animQueue);

return this;
},

stop : function (clearQueue) {
if (clearQueue) HR._animQueue.length = 0;
this.each(function (el) {
if (!!HR.timers[el.id])
for (var i=0; i});
return this;
},

execute : function (queue) {
var _this = this, m = 0, n = 0,
_anim = function (el, key, from, to, at, tw, ease, cb) {
var isOP = (key == 'opacity' && !HR.support.opacity), _key = key;
if (isOP) {to = to*100; _key = 'filter'}
var s = new Date,
d = at,
b = parseFloat(from) || 0,
c = to-b;

(function () {
var t = new Date - s;
if (t >= d) {
n ;
t = d;
el.style[_key] = (isOP ? 'alpha(opacity=' : '') Tween.Linear(t, b, c, d) (key != 'opacity' ? 'px' : '') (isOP ? ')' : '');
!!cb && cb.apply(el);
if (m == n && _this.animQueue.length > 1) {
_this.animQueue.shift();
_this.execute(_this.animQueue);
}

return;
}
el.style[_key] = (isOP ? 'alpha(opacity=' : '') Tween[tw][ease](t, b, c, d) (key != 'opacity' ? 'px' : '') (isOP ? ')' : '');

if (!HR.timers[el.id]) HR.timers[el.id] = [];
HR.timers[el.id].push(setTimeout(arguments.callee, 16));

})();
},
_q = this.animQueue[0];

return this.each(function (el) {
for (var k in _q.config) {
m ;
_anim(el,
k,
k == 'opacity' && !HR.support.opacity ? HR.getStyle('filter', el) == '' ? 100 : parseInt(HR.getStyle('filter', el).match(/d{1,3}/g)[0]) : HR.getStyle(k, el),
_q.config[k],
typeof _q.time == 'number' ? _q.time : 1000,
typeof _q.tween == 'string' && !/^ease*/.test(_q.tween) ? _q.tween : 'Quart',
typeof _q.ease == 'string' && /^ease*/.test(_q.ease) ? _q.ease : 'easeOut',
_q.callback)
}
});
}
}

HR.extend(HR, {
get : function () {
return new get(arguments);
},
isFunction : function(o) {
return typeof(o) == 'function' && (!Function.prototype.call || typeof(o.call) == 'function');
},
getStyle : function (p, el) {
return el.currentStyle ? el.currentStyle[p] : document.defaultView.getComputedStyle(el, null).getPropertyValue(p);
},
support : (function () {
try {
var d = document.createElement('div');
d.style['display'] = 'none';
d.innerHTML = '';
var a = d.getElementsByTagName('a')[0];
return {
opacity: a.style.opacity === '0.5'
}
} finally {
d = null;
}
})(),

timers : {}

});
})();


Then in order to make it more intuitive for everyone, I made two demos
【demo1】

[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
]
[demo2]
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
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.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

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 the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

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

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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.

mPDF

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),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment