先导入1.11.0的js包,在新建一个js文件导入,
<script type="text/javascript" src="js/jquery-1.11.0.js" ></script>
<script type="text/javascript" src="js/center-1.3.js" ></script>
先在html写出div的ID或者class
<body>
<div id="box"></div>
</body>
在写js的时候记得开始要加一个分号( ; )
这些写出
;(function($){
})(jQuery)
后面定义一个方法和这个方法的名字
;(function($){
$.fn.center = function(options){
}
})(jQuery)
接着我们写出盒子的样式
;(function($){
//对象级别
$.fn.center = function(options){
var defaults = {
"position":"absolute",
"background":"red",
"width":100,
"height":100
}var options = $.extend(defaults,options);
return this
})(jQuery)
接着就是功能实现逻辑
;(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
}
})(jQuery)
在最后加上一个随页面变化
$(window).resize(function(){
_this.css({
"left":($(window).width()-options.width)/2,
"top":($(window).height()-options.height)/2
})
最后保存,在html运行
<script>
$("#box").center()
</script>
一下是js的全部代码
;(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
})
$(window).resize(function(){
_this.css({
"left":($(window).width()-options.width)/2,
"top":($(window).height()-options.height)/2
})
})
})
return this
}
})(jQuery)