寫一寫jquery插件的編寫方法
使用階段
引入jQuery.js
引入jquery.plugin.js
調用$.plugin() 或者 $(selector).plugin()
為了提升自己,同時也是應對不同業務的需要,自己會寫jQuery插件是一件不得不做的事情,而且是一件令人愉快的事情,本文就先從jQuery的類插件開發做一點自己的分享.
案例,讓id為div1的元素相對屏幕居中,用jQuery插件實現
#div1{
width: 100px;
height: 100px;
background-color: green;
}
<div id="div1"></div>
方法1 --屬性方法
$.center = function(obj){
$(obj).css({
'top': ($(window).height() - $(obj).height()) / 2,
'left': ($(window).width() - $(obj).width()) / 2,
'position': 'absolute'
})
return $(obj);
}
//調用方法
$.center('#div1')
方法2--合并對象
$.extend({
center: function(obj){
$(obj).css({
'top': ($(window).height() - $(obj).height()) / 2,
'left': ($(window).width() - $(obj).width()) / 2,
'position': 'absolute'
})
return $(obj);
}
})
//調用方法
$.center('#div1')
方法3--命名空間避免沖突
$.fangdown = {
center: function(obj){
$(obj).css({
'top': ($(window).height() - $(obj).height()) / 2,
'left': ($(window).width() - $(obj).width()) / 2,
'position': 'absolute'
})
return $(obj);
}
}
//調用方法
$.fangdown.center('#div1')