jQuery扩展方法

最近整理了一下jQuery扩展方法,如下

(function($) {
    // 1. 滚动条滚动动画
    $.fn.scrollTo = function(options) {
        options = $.extend({
            scrollLeft: 0,
            scrollTop: 0,
            speed: 200 //unit:ms
        }, options);

        this.stop()
            .animate({ scrollLeft: options.scrollLeft, scrollTop: options.scrollTop }, options.speed);

        return this;
    };

    // 2. 设置 div 在屏幕中央
    $.fn.center = function() {
        var $win = $(window);
        this.css({
            'position': 'absolute',
            'top': ($win.height() - this.height()) / 2 + $win.scrollTop() / 2,
            'left': ($win.width() - this.width()) / 2 + $win.scrollLeft() / 2
        });
        return this;
    };

    // 3. 检测鼠标的右键和左键
    $('body').mousedown(function(e) {
        alert(e.which); // 1: 鼠标左键 2:鼠标中键 3:鼠标右键
    });

    // 4. 回车提交表单
    $(':text, :password').keyup(function(e) {
        if (e.which == "13") {
            alert('回车提交');
        }
    });

    // 5. 扩展 String 对象的方法
    $.extend(String.prototype, {
        isPositiveInteger: function() {
            return /^[1-9]+\d*$/.test(this);
        },
        isInteger: function() {
            return /^\d+$/.test(this);
        },
        isNumber: function() {
            return /^-?([0-9]*)(\.[0-9]+)?$/.test(this);
        },
        ltrim: function() {
            return this.replace(/^\s+/, '');
        },
        rtrim: function() {
            return this.replace(/\s+$/, '');
        },
        trim: function() {
            return this.replace(/(^\s+*)|(*\s+$)|\r|\n/g, '');
        }
    });

    // 6.数字转成千分位字符串
    // 注意:使用时,不能直接 123.toCurrencyString(),应该先定义变量,如:var num = 123; num.toCurrencyString();
    $.extend(Number.prototype, {
        toCurrencyString: function() {
            // 匹配每一个数字,找到右边含有三个小数点且有3个倍数个数字的数字,将其替换为本身加逗号
            return this.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
        }
    });

    // 7. 输入框/下拉框/单选按钮/checkbox只读/取消只读
    $.fn.Lockdown = function(lock) {
        var lock = typeof(lock) == "undefined" ? true : lock;
        if (this.is('select')) {
            // 对于select,使用时,外面需要嵌套一个block的元素
            if (lock) {
                if (this.prev('[name=mask_layer]').length == 0) {
                    var scrollTop = $('body').scrollTop();
                    var scrollLeft = $('body').scrollLeft();
                    this.css('color', '#666');
                    this.before('<div name="mask_layer" style="width:' + (this.width() + 4) + 'px;height:' +
                        (this.height() + 2) +
                        'px;background-color:#666;opacity:.10;position:absolute;"></div>');
                }
            } else {
                this.css('color', 'black');
                this.parent().find('div[name=mask_layer]').remove();
            }

        } else if (this.is(':radio') || this.is(':checkbox')) {
            var n = this.attr('name');
            var v = $('[name=' + n + ']:checked').val();
            var es = $('[name=' + n + ']').not(':hidden');

            $('input[name=' + n + '][type=hidden]').remove(); //remove old hidden input
            if (lock && typeof(v) != 'undefined') {
                debugger
                var c = $('<input type="hidden" />')
                c.attr('name', n)
                c.val(v);
                this.parent().append(c);
            }

            es.each(function() {
                $(this).prop('disabled', true);
            });

        } else { 
            if (lock) {
                $(this).attr("readonly", true);
            } else {
                $(this).attr("readonly", false);
            }

        }
    };

    // 8. 移除输入的数字开头的0
  $.extend({
        removeZeroInStartForMoneyFilter: function() {
            $("div[filter*=MONEY] > input").blur(function() {
             // 传入,则如果开头出现0,则弹出错误信息;否则,直接移除开头的0
                var moneyCheck = $(this).attr('moneycheck');
                // 输入的数字是否可以等于0,如果可以为0,则多个0时只保留1个0
                var canBeZero = $(this).attr('canbezero');
                var $cur = $(this);
                var val = $cur.val();
                var msg = $cur.parent().find('span').text();


                if (typeof(canBeZero) != 'undefined' && val.replace(/,/g, '').search(/^(\$)?0+(\.[0]+)?$/) == 0) {
                    // value can be zero and is zero, just reserve one zero
                    $cur.val('$0');
                } else if (typeof(moneyCheck) == 'undefined') {
                    // If without moneycheck attribute, just remove zero in start
                    var tmp = val.replace(/^([$])?(0(,)?)+(?![.])/, '');
                    tmp = tmp[0] == '$' ? tmp : '$' + tmp;
                    $(this).val(tmp);
                } else if (val.replace(/,/g, '').search(/^(\$)?0+(\.[0]+)?$/) == 0) {
                    // If can not be zero and is zero and money check needed, alert prompt
                    alert(msg + ' must be greater than 0.');
                } else {
                    // If with moneycheck attribute, don't remove zero in start, just alter prompt
                    if (val != '' && val.search(/^(\$)?(0)+(?!\.)/) == 0) {
                        alert(moneyCheck + ' cannot begin with a zero.');
                    }
                }


            }).focus(function() {
                var moneyCheck = $(this).attr('moneycheck');
                if (typeof(moneyCheck) == 'undefined') {
                // 获取焦点时移除开头的0
                    $(this).val($(this).val().replace(/^(0)+(?![.])/, ''));
                }
            });
        }
  });

// 9. 日期格式化
Date.prototype.pattern = function dateFormat(fmt) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12,
        "H+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
    };
    var week = {
        "0": "/u65e5",
        "1": "/u4e00",
        "2": "/u4e8c",
        "3": "/u4e09",
        "4": "/u56db",
        "5": "/u4e94",
        "6": "/u516d"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
    }
})(jQuery);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于开发 jQuery 火狐扩展,你可以遵循以下步骤: 1. 准备工作:确保你已经安装了最新版本的 Firefox 浏览器和一个文本编辑器(如 Visual Studio Code)。 2. 创建扩展文件夹:在你的工作目录下创建一个新的文件夹,用作扩展的根目录。 3. 创建 manifest.json 文件:在扩展的根目录中创建一个名为 manifest.json 的文件。这个文件用于描述扩展的元数据,包括名称、版本号、描述等。 4. 编写代码:在根目录中创建一个名为 content.js 的 JavaScript 文件,用于编写你的 jQuery 代码。在这个文件中,你可以使用 jQuery 库进行 DOM 操作和事件处理等。 例如,你可以编写一个示例代码来修改当前页面的标题: ```javascript $(document).ready(function() { $('title').text('Hello, Firefox Extension!'); }); ``` 5. 引入 jQuery 库:将 jQuery 库文件(例如 jquery.min.js)下载并放置在根目录中。然后,在 content.js 文件中通过以下方式引入 jQuery 库: ```javascript importScripts("jquery.min.js"); ``` 6. 更新 manifest.json 文件:在 manifest.json 文件中添加必要的配置项,以便 Firefox 可以正确加载和运行你的扩展。具体配置可以参考 Mozilla 开发者文档。 7. 打包扩展:将扩展文件夹压缩为一个 ZIP 文件,确保不包含额外的文件或文件夹。 8. 安装扩展:打开 Firefox 浏览器,点击菜单按钮,选择“附加组件”进入附加组件管理页面。在页面右上角的齿轮图标下拉菜单中选择“从文件安装附加组件”,然后选择之前打包好的 ZIP 文件进行安装。 9. 调试和测试:在 Firefox 中打开网页,并检查扩展是否按预期运行。在开发过程中,你可以通过 Firefox 的开发者工具来调试和测试你的扩展。 请注意,上述步骤只是一个简单的概述,实际开发过程中可能会涉及到更多细节和特定要求。你可以参考 Mozilla 开发者文档中关于 Firefox 扩展的详细指南,以更好地了解和掌握开发流程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值