插件的框架代碼:
;(function($){
$.fn.extend({ // **$.fn.extend表示要創(chuàng)建一個對象級別的插件**
"border":function(value){
//這里寫插件代碼
}
});
})(jquery)
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="js/jquery-2.2.2.min.js"></script>
<script src="jquery.border.js"></script>
<script type="text/javascript">
$(function() {
$("#test").border({
width: "5px",
"line": "dotted",
color: "blue"
}).css("background", "green");
});
</script>
<style type="text/css">
body {
margin: 20px;
}
#test {
font-size: 9pt;
width: 300px;
height: 50px;
line-height: 50px;
font-weight: bold;
color: snow;
padding-left: 20px;
}
</style>
</head>
<body>
<div id="test">這個示例演示了自定義對象級別的插件的使用方法</div>
</body>
</html>
jquery.border.js:
模板要點:
1.函數(shù)全部放在閉包里,外面的函數(shù)就調(diào)用不到里面的參數(shù)了,比較安全
2.前面加分號,避免不必要的麻煩
;(function ($) {
$.fn.extend({
//為jquery添加一個實例級別的border插件
"border": function (options) {
//設(shè)置屬性
options = $.extend({
width: "1px",
line: "solid",
color: "#090"
}, options);
this.css("border", options.width + ' ' + options.line + ' ' + options.color);
//設(shè)置樣式
return this;
}
})
})(jQuery)
result:

image.png