写了个限制文本框输入最大长度的jquery插件

做了个限制文本框最大输入长度的jquery插件,效果图(共2个文本框,限制最多10个字符):

 

功能:当超出设置的最大字符长度后,会截断字符串、更改当前元素的css(会在1秒后还原css)、支持长度超出后的异常回调

使用方式:

<body>
    <textarea id="filter1" rows="5" cols="100"></textarea>
    <textarea id="filter2" rows="5" cols="100"></textarea>
    <br />
    <span id="msg"></span>
    <script language="javascript" type="text/javascript">
        $(function () {
            function processException(id) {
                $("#msg").html(id + "&nbsp;exception occurred.<br />" + $("#msg").html());
            }

            $("#filter1,#filter2").restrictFieldLength({
                maxTextLength: 10,
                restoreTime:2000,
                exceptionCallback: processException
            });
        });
    </script>
</body>

jquery.restrictFieldLength.js:

(
    function ($) {
        $.fn.restrictFieldLength = function (settings) {
            var opts = $.extend({}, $.fn.restrictFieldLength.defaultSettings, settings || {});

            return this.each(function () {
                var elem = $(this);

                elem.on("keyup", function () {
                    var s = elem.val();
                    if (s.length >= opts.maxTextLength) {
                        elem.val(s.slice(0, opts.maxTextLength));
                        elem.prop("class", opts.exceptionCss);
                        if (opts.exceptionCallback) {
                            opts.exceptionCallback(elem[0].id);
                        }
                        var normalIt = function () {
                            elem.prop("class", opts.defaultCss);
                        }
                        setTimeout(normalIt, opts.restoreTime);
                    }
                });
            });
        }
        $.fn.restrictFieldLength.defaultSettings = {
            maxTextLength: 100,
            defaultCss: "restrictFieldLength_defaultCss",
            exceptionCss: "restrictFieldLength_exceptionCss",
            restoreTime:1000,
            exceptionCallback: null
        }
    }
)(jQuery);

jquery.restrictFieldLength.css

.restrictFieldLength_defaultCss
{
    color:black;
}
.restrictFieldLength_exceptionCss
{
    color:red;
}
原文地址:https://www.cnblogs.com/aarond/p/3234042.html