仿得微博字符限制效果

呃。貌似好久没有写日志了。。最近忙的天天想发飙。。。今天得空备份一下项目中用到的小技巧等等吧。。看到过的大神请忽略。。我就是个前端小猫而已~~~

公司项目中有个这样的东西,大家用微博的都明白哈~~

这是初始状态

输入文字变成这样,这里会区分圆角半角,2个半角的文字算一个。

这个是超出的样子

如果超出了点击提交,会有红色闪动提示

好了,效果就是这样子,都是js的。。用的话,记得加个jq文件过来。。

这里是超出只有提示,还可以超出以后截掉多余的。。不过公司项目不用,说是体验不好~~~

var oH2 = $("#spetit_word");//提示文字
var oTextarea = $("#p_qa_content");//输入框
var oButton = $("#bt-ico");//按钮
oTextarea.live("keyup", function () {
        Limit(oTextarea, 280, oH2);
})
oButton.live("click", function () {
        if (font_count < 0 || font_count == null || font_count == 140) {
            Error(oTextarea);
        } else {           
            alert('发布成功!');
        }
});
var font_count;

function WordLength(obj) {
        var oVal = obj.val();
        var oValLength = 0;
        oVal.replace(/\n*\s*/, '') == '' ? oValLength = 0 : oValLength = oVal.match(/[^ -~]/g) == null ? oVal.length : oVal.length + oVal.match(/[^ -~]/g).length;
        return oValLength
}
function Error(obj) {
        var oTimer = null;
        var i = 0;
        oTimer = setInterval(function () {
            i++;
            i == 5 ? clearInterval(oTimer) : (i % 2 == 0 ? obj.css("background-color", "#ffffff") : obj.css("background-color", "#ffd4d4"));
        }, 100);
}
//obj-要检查的输入框, iNow-多少字, tit-提示框
function Limit(obj, iNow, tit) {
        var oValLength = WordLength(obj);
        font_count = Math.floor((iNow - oValLength) / 2);
        if (font_count >= 0) {
            tit.html("你还可以输入<strong>" + font_count + "</strong>字");
            return true;
        } else {
            tit.html("已超出<strong style='color:red'>" + Math.abs(font_count) + "</strong>字");
            return false;
        }
        return font_count;
}
一只喜欢烘焙的IT喵星人
原文地址:https://www.cnblogs.com/CherryGhost/p/2451862.html