jQuery插件的封装
$.fn上面添加一个方法
当需要给jQuery对象 增加方法时,可以设置$.fn下面添加一个方法
这样添加好以后,jQuery对象就有这个方法了
div{
width: 50px;
height: 50px;
background-color: aqua;
position: absolute;
left: 300px;
top: 200px;
}
<div></div>
<div id="divs"></div>
<div></div>
<div></div>
<p></p>
<p></p>
<p></p>
// 当需要给jQuery对象 增加方法时,可以设置$.fn下面添加一个方法
// 这样添加好以后,jQuery对象就有这个方法了
(function(){
// 给jQuery.fn加入新的功能属性,添加的对象属性的名称就是插件的名称
$.fn.bg=function(color){
// 增加id判断方式
if (this.attr("id") !== "divs" || this.length > 1) return this;
// this 就是调用该方法的jQuery对象
// 当color没有时,就将颜色结果返回出去
if(color===undefined) return this.css("backgroundColor");
this.css("backgroundColor",color);
return this;
};
$.fn.pos=function(posObj){
if(posObj===undefined){
return{
left:parseFloat(this.css("left")),
top:parseFloat(this.css("top")),
};
}
this.css({
position: "absolute",
left:String(posObj.left).indexOf("px")>-1 ? posObj.left: posObj.left + "px",
top:String(posObj.top).indexOf("px")>-1 ? posObj.top: posObj.top + "px",
})
}
})();
// $("div").width(100).height(100).bg("red");
// $("<div></div>").appendTo("body").width(100).height(100).bg("yellow");
// $("div").width(100).height(100).bg("pink");
// $("p,div").width(100).height(100).bg("pink");
// $("<div></div>").width(100).height(100).bg("green").appendTo("body")
// $("#divs").width(100).height(100).bg("red");
// console.log($("div").bg());
// $("div").pos({left:1000});
// console.log($("div").pos());
// $("#divs").width(100).height(100).bg("blue");
$.extend()向jquery中添加函数
// var arr=[1,2,3,4];
// var arr={a:1,b:2,c:3};
// $.each(arr,function(index,item){
// })
// console.log(new arr.constructor());
// $.extend()向jquery中添加函数
// filter方法对象数组都可以使用
$.extend({
filter:function(list,fn){
// 根据对象创建构造函数,创建这类型的对象,是数组就创建数组,对象就创建对象
var newList=new list.constructor();
// 当传进来的参数等于jQuery对象时,按数组的方式添加
if(list.constructor===jQuery){
newList=[];
}
// 遍历list
for(var prop in list){
// 执行函数将传进来的list的属性和属性值作为参数带入进去
// 判断执行函数后返回的是true还是fasle
if(fn(prop,list[prop])){
// 判断创建的对象是不是数组
// 如果是,就将过滤出来的结果添加到数组中
if(Array.isArray(newList)){
newList.push(list[prop]);
}else{
// 对象属性的添加
newList[prop]=list[prop];
}
}
}
// 数组转换为jQuery对象
if(list.constructor===jQuery){
newList=$(newList);
}
return newList;
},
randomColor:function(){
var color="#";
for(var i=0;i<6;i++){
color+=Math.floor(Math.random()*16).toString(16);
}
return color;
}
});
var arr=[2,4,3,1,5,6];
var arr={a:1,b:2,c:3,d:4}
var list=$.filter($("div"),function(prop,item){
// console.log(prop,item);
// return item>2;
return item.id==="divs";
})
console.log(list);
list.css("backgroundColor","red");
$("div").bg($.randomColor());