美文网首页
jQuery类插件编写方法

jQuery类插件编写方法

作者: fangdown | 来源:发表于2017-05-17 09:02 被阅读0次

    写一写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')
    

    相关文章

      网友评论

          本文标题:jQuery类插件编写方法

          本文链接:https://www.haomeiwen.com/subject/kanrxxtx.html