摘要:[jQuery] 簡單寫Plugin
網路上有很多的jQuery高手,常常寫出很多很華麗的plugin來給人使用
但要寫個jQuery的Plugin其實並不困難,
在這邊提供一個簡單的方法,剛好也可以自己做個筆記,
如果不熟的話,就把他的架構當作公式背,很容易就可以寫出一個自己的Plugin,











這是我自己常用的架構,$在jQuery中,常常是用來宣告這是jQuery的程式,
但首先要注意到為了避免有其他的程式把$用掉,
我們要強制在結尾加上(jQuery),使$在這個程式中是給jQuery使用,
$.fn.[Plugin名稱] 就是可以設定你Plugin的名稱,比方說你可以寫成 $.fn.TEST,
在頁面使用時就可以用 TEST({......}); 來呼叫你的plugin,
而上方有一塊是可以設定你的屬性值,這邊可由你自己規劃你所要帶的一些屬性(可使用OO 的想法去思考),
然後你可以設定這些屬性值是否要有預設值,
接下來主程式的區塊,就是用來撰寫這隻程式主要的部分,
我提供前陣子幫我們美術人員撰寫一個簡單的Plugin來當範例,
這隻Plugin主要的功用就是可以按下按鈕就可以縮合某個區域,再按一次就可以展開,
這程式在jQuery中非常簡單,只要知道hide和show就可以輕鬆寫出,
而hide的原理,其實就是把這包裹元素加上CSS的display:none; 程式部分如下,




































像程式我就設定了幾個屬性:
ClickBlock: "#link1", //click的區域
ControlBlock: "#block1", //反應的區域
isUseCSS: "Y", //反應區域是否要使用CSS的Class
ShowClass: "clickopen", //反應區域在Show狀態的Class
HideClass: "clickclose" //反應區域在Hide狀態的Class
這些屬性值都是可以讓user在套用plugin時可以修改的部分,
而在主程式的部分只是做一些簡單的判斷,當按下按鈕時若是隱藏的就會展開,反之就隱藏,
然後可以選擇是否要在按鈕使用CSS,讓按鈕在隱藏狀態和顯示狀態是不一樣的,
最後在頁面呼叫時程式如下
<head>
<title>My Hide</title>
<script src="js/jquery-1.3.2.js" type="text/javascript" charset="utf-8"></script>
<script src="js/MyHide.js" type="text/javascript" charset="utf-8"></script>
<script language="javascript" type="text/javascript">
$().ready(function () {
$().myhide({
ClickBlock: "#click1",
ControlBlock: "#block",
isUseCSS: "Y",
ShowClass: "open",
HideClass: "close"
});
});
</script>
<style type="text/css">
.open
{
background-color:Lime;
width:200px;
height:50px;
display:block;
}
.close
{
background-color:Maroon;
width:200px;
height:50px;
display:block;
}
</style>
</head>
<body>
<div id="click1" class="open">
click me
</div>
<div id="block" style="background-color:Blue; width:300px; height: 200px; display:block;"></div>
<div id="block2" style="background-color:Green; width:400px; height: 200px; display:block;"></div>
</body>
</html>
範例檔 : MyHide.rar