1.创建一个html文件和js文件,并将js文件连接到HTML文件了,还有将jquery包导入html文件中
<script type="text/javascript" src="js/jquery-1.11.0.js" ></script>
<script type="text/javascript" src="js/center-1.2.js" ></script>
<style>
*{margin: 0;}
</style>
</head>
<body>
<div id="box">
</div>
<script>
$("#box").center({
})
</script>
2.通过jquery中的$.fn对外暴露方法,要注意开头一定要加分号“;”
;(function($){
$.fn.center = function(options){
})
3.利用$.extend合并默认参数(defaults)和形参(options),在extend里后面的形参改变前面的参数,如果没有后面的形参就直接继承
;(function($){
//对象级别
$.fn.center = function(options){
var defaults = {
"position":"absolute",
"background":"red",
"width":100,
"height":100
}
var options = $.extend(defaults,options);
})
4.实现逻辑功能,这里的this是指的是jq的盒子
;(function($){
//对象级别
$.fn.center = function(options){
var defaults = {
"position":"absolute",
"background":"red",
"width":100,
"height":100
}
var options = $.extend(defaults,options);
this.each(function(){
//功能实现逻辑
var _this = $(this)
})
5.实现盒子的水平垂直居中的公式
var _vH = ($(window).height()-options.height)/2
var _vW = ($(window).width()-options.width)/2
6.对象级别开发插件模板
;(function($){
//对象级别
$.fn.center = function(options){
var defaults = {
"position":"absolute",
"background":"red",
"width":100,
"height":100
}
var options = $.extend(defaults,options);
this.each(function(){
//功能实现逻辑
var _this = $(this)
var _vH = ($(window).height()-options.height)/2
var _vW = ($(window).width()-options.width)/2
_this.css({
"background":options.background,
"position":options.position,
"width":options.width,
"height":options.height,
"left":_vW,
"top":_vH
})
})
return this
最后一点要return this实现连缀。这里的this是jq的this对象