基础就不说了,下面是直接贴源代码

 (function ($) {
            $.extend($, { fixedWidth: function (str, length, char) {
                str = str.toString();
                if (!char) {
                    char = "...";
                }
                var num = length - lengthB(str);

                if (num < 0) {
                    str = substringB(str, length - lengthB(char)) + char;
                }
                return str;

                function substringB(str, length) {
                    var num = 0;
                    var len = str.length;
                    var tem = "";
                    if (len) {
                        for (var i = 0; i < len; i++) {
                            if (num > length) {
                                break;
                            }
                            if (str.charCodeAt(i) > 255) {
                                num += 2;
                                tem += str.charAt(i);

                            } else {
                                num++;
                                tem +=str.charAt(i);
                            }
                        }
                    }
                    return tem;
                }

                function lengthB(str) {
                    var len = str.length;
                    var num = 0;
                    if (len) {
                        for (var i = 0; i < len; i++) {
                            if (str.charCodeAt(i) > 255) {
                                num += 2;
                            }
                            else {
                                num++;
                            }
                        }
                    }
                    return len;
                }
            }
            });
        })(jQuery)

 

用法不是很难,下面是具体的用法

方法:

  function clkfun() {
            var value = $("#txtInput").val();
            $("#fixedID").text($.fixedWidth(value, 9));

        }

HTML页面

<body>
    <div>
        <div id="fixedID" style="margin: 0px; padding: 0px; width: 55px; height: 24px; line-height: 24px; font-size:12px;
            border: 1px solid  red; overflow: hidden;">
        </div>
        <div>
            <input type="text" name="txtInput" value="45646464646" id="txtInput" />
            <input type="button" name="btnClick" value="Click " onclick="clkfun();" />
        </div>
    </div>
    <form id="form1" runat="server">
    <div>
        <div>
        </div>
    </div>
    </form>
</body>

 

posted on 2012-07-01 20:10  gzh4455  阅读(136)  评论(0编辑  收藏  举报