概述:微博上有 自动提示 微博字符 的功能,在此有人一直用 “onpropertychange” 事件,但是这个事件在 火狐下是不支持的。所以为弥补这种浏览器不兼容的缺陷,我写了一个 demo供大家参考。
分析:阅读相关W3c资料,想在火狐下兼容 类似 IE 中“onpropertychange”的事件,必须添加 一个名叫 “input”的事件监听器 于 你的 textArea中。
废话不多说了,也许说的都是废话。
实践:
公共页面:
(1)JS方式:
2:Jquery方式,建议大家用jquery方式,速度效率上比 js 方式都好。
注意:TextArea的ID与消息的提示的ID 要关联起来。
【<textarea id="msgTxt" 】
【<span id="msgTxtCountTxt">还能输入 <em class="msblogMsg">140</em> 字</span>】
童鞋们请看, msgTxt 与 msgTxtCountTxt 是有关联的哦。这样做的好处是:即使页面上有多个 不同元素 的 textarea ,你只需要给:addCheck(msgTxt); 传个参数就行。其余的根据这个规范来。
好了,到此结束。
分析:阅读相关W3c资料,想在火狐下兼容 类似 IE 中“onpropertychange”的事件,必须添加 一个名叫 “input”的事件监听器 于 你的 textArea中。
废话不多说了,也许说的都是废话。
实践:
公共页面:
<style type="text/css">
.msblogError,.msblogMsg{font-family:Georgia,Tahoma,Arial;font-size:26px;font-weight:400;font-style:normal;line-height:33px;word-spacing:0;vertical-align:middle;}
.msblogError{color:#E56C0A;}
.msblogMsg{color:#999999;}
</style>
<p><form>
<textarea id="msgTxt" name="Content" autocomplete="off" tabindex="1" rows="7" class="w500"></textarea>
</form></p>
<p>
<span id="msgTxtCountTxt">还能输入 <em class="msblogMsg">140</em> 字</span>
<button type="button" id="btnFabu" title="快捷键 Ctrl+Enter" tabindex="2">发布</button></p>
(1)JS方式:
<script type="text/javascript">
window.onload=function()
{
if(navigator.userAgent.indexOf("MSIE")>0) //ie浏览器
{
document.getElementById('msgText').attachEvent("onpropertychange",TxtMaxlength);
}else
{
document.getElementById('msgText').addEventListener("input",TxtMaxlength,false);
}
};
function TxtMaxlength(){
MaxCount=140;
var $=function(id){return document.getElementById(id);}
var ObjCou=$('msgTxt').value.length;
$($("MsgTxt").id+"CountTxt").getElementsByTagName("em")[0].innerHtml=MaxCount-ObjCou;
if (ObjCou > MaxCount){
$("msgTxtCountTxt").innerHtml="超出<em class='msblogError'>"+ (ObjCou-MaxCount) +"</em>字";
}else{
$("msgTxtCountTxt").innerHtml="还能输入<em class='msblogMsg'>"+ (MaxCount-ObjCou) +"</em>字";
}
}
</script>
2:Jquery方式,建议大家用jquery方式,速度效率上比 js 方式都好。
<script type="text/javascript">
$(function () {
addCheck('msgTxt');
});
function addCheck(id){
$('#'+id).bind('propertychange input',TxtMaxlength);
}
function TxtMaxlength(){
MaxCount=140;
var ObjCou=$(this).attr("value").length;
$("#"+this.id+"CountTxt em").html(MaxCount-ObjCou);
if (ObjCou > MaxCount){
$("#"+this.id+"CountTxt").html("超出<em class='msblogError'>"+ (ObjCou-MaxCount) +"</em>字");
}else{
$("#"+this.id+"CountTxt").html("还能输入<em class='msblogMsg'>"+ (MaxCount-ObjCou) +"</em>字");
}
}
</script>
注意:TextArea的ID与消息的提示的ID 要关联起来。
【<textarea id="msgTxt" 】
【<span id="msgTxtCountTxt">还能输入 <em class="msblogMsg">140</em> 字</span>】
童鞋们请看, msgTxt 与 msgTxtCountTxt 是有关联的哦。这样做的好处是:即使页面上有多个 不同元素 的 textarea ,你只需要给:addCheck(msgTxt); 传个参数就行。其余的根据这个规范来。
好了,到此结束。