仿微博字符限制效果实现代码

  这是初始状态

仿微博字符限制效果实现代码

  输入文字变成这样,这里会区分圆角半角,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;

  }