在這簡單做一個說明方塊的範例,點擊時會在該物件下面顯示方塊,點別的地方會消失

<html>
<head>
<title>jqury plugin</title>
<style>
#helpBox 
{
    position      : absolute; 
    padding       : 5px;  
    border-radius : 5px;
    border        : 1px solid #ccc; 
    z-index       : 999; 
    background    : #eeF;
}
</style>
<script type="text/javascript" src='jquery.js'></script>
<script>
(function($)
{
    $.fn.helpBox = function (msg) 
    {
        // 指定移除 box 的事件
        var remove_this = function(event){$('#helpBox').remove(); }

        // 只能有一個 helpBox
        remove_this();

        // 加上 box 
        this.append("<div id='helpBox'>" + msg + "</div>");

        // 指定位置
        var position = this.position();
        var size     = this.size();
        var x = position.left;
        var y = position.top + size.height;
        $('#helpBox').css({left:x, top:y});

        // 註冊移除 helpBox 的事件
        $(document).bind('click', remove_this);

        // 讓 jquery 可以繼續串接
        return this;
    };
})(jQuery);


$(function()
{
    $('p, #content').bind('click', function (event) 
    {
        event.stopPropagation();
        $(this).helpBox('Hello World!');
    });
});
</script>
</head>
<body>
<div id='base' style='margin:0 auto; width:600px;'>
    <p>123123</p>
    <p>123123</p>
    <p>123123</p>
    <p>123123</p>
    <div id='content'>在這裡出現吧</div>
</div>
</body>
</html>

 
這裡有幾點要注意的地方
1. 這裡使用立即函式來建立 plugin ,其實也可以用官網的寫法 jQuery.fn.functionName = function (){}; 的這種寫法
2. 在 plugin 的 function 裡,this 代表的是 jQuery 已經選擇的那個物件
3. 如果要維護 jQuery 串接的寫法,最後要 return this
 

arrow
arrow
    全站熱搜

    wbkuo 發表在 痞客邦 留言(0) 人氣()