JQ的调用方式是链式调用
例:
$().css().animate().css()
JQ封装演变过程:
加点:
对象.属性
var obj={
a:{
b:function(){}
}
}
obj.a.b
加括号:
function $() {
return {
css: function() {},
animate: function() {}
}
}
$().css()
继续调用当前或其它属性:
function $(){
return {
css:function(){
return this;
},
animate:function(){
return this;
}
}
}
$().css().animate().css()
将方法挂载到对象原型上(原先的相当于每使用一次方法相当于创建一次对象,现在的相当于从对象原型上调用方法):
Object.prototype.css = function() {
return this;
}
Object.prototype.animate = function() {
return this;
}
function $() {
return {}
}
$().css().animate().css()
对象和方法太多容易造成混乱,可修改如下:
Object.prototype= {
css:function(){
return this;
},
animate:function(){
return this;
}
}
function $() {
return {}
}
$().css().animate().css()
出错了,Object不能等于自己{ },可修改如下:
Base.prototype= {
css:function(){
return this;
},
animate:function(){
return this;
}
}
function $() {
var base=new Base()
return base
}
function Base(){}
$().css().animate().css()
获取元素:
Base.prototype= {
css:function(){
console.log(this.el);
return this;
}
}
function $(select) {
var nodeList=document.querySelectorAll(select)
var base=new Base(nodeList)
return base
}
function Base(node){
this.el=node
}
$('.box').css()
设置属性:
Base.prototype= {
css:function(){
for(var i=0;i<this.el.length;i++)
{
this.el[i].style.width='100px';
this.el[i].style.height='100px';
this.el[i].style.backgroundColor='red';
}
return this;
}
}
function $(select) {
var nodeList=document.querySelectorAll(select)
var base=new Base(nodeList)
return base
}
function Base(node){
this.el=node
}
$('.box').css()
设置传入的属性:
Base.prototype= {
css:function(attr){
for(var i=0;i<this.el.length;i++)
{
this.el[i].style.width=attr.width;
this.el[i].style.height=attr.height;
this.el[i].style.backgroundColor=attr.backgroundColor;
}
return this;
}
}
function $(select) {
var nodeList=document.querySelectorAll(select)
var base=new Base(nodeList)
return base
}
function Base(node){
this.el=node
}
$('.box').css({
width:"100px",
height:"100px",
backgroundColor:"green"
})
传入什么属性修改什么属性:
Base.prototype= {
css:function(attr){
for(var i=0;i<this.el.length;i++)
{
for(var j in attr){
this.el[i].style[j]=attr[j];
}
}
return this;
}
}
function $(select) {
var nodeList=document.querySelectorAll(select)
var base=new Base(nodeList)
return base
}
function Base(node){
this.el=node
}
$('.box').css({
width:"100px",
height:"100px",
backgroundColor:"green"
})
可以选择某个节点(需要在仔细思考一下):
Base.prototype= {
css:function(attr){
for(var i=0;i<this.length;i++)
{
for(var j in attr){
this[i].style[j]=attr[j];
}
}
return this;
}
}
function $(select) {
var nodeList=document.querySelectorAll(select)
var base=new Base(nodeList)
for(var i=0;i<nodeList.length;i++){
base[i]=nodeList[i]
}
base.length=nodeList.length
return base
}
function Base(){}
$('.box').css({
width:"100px",
height:"100px",
backgroundColor:"green"
})
console.log($(".box")[0]);