利用JavaScript做出即時統計文章內容字元數
最近有一個網友問到這個問題....
去找了別人討論區發文的功能....
偷偷看了一下程式碼....原來是用javascript就可以做到了....
在此分享給大家呀.....
c#範例
ComputeWordNum.aspx
01 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ComputeWordNum.aspx.cs" Inherits="ComputeWordNum" %>
02
03 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04 <html xmlns="http://www.w3.org/1999/xhtml">
05 <head id="Head1" runat="server">
06 <title>未命名頁面</title>
07
08 <script language="javascript" type="text/javascript">
09 function ComputeWordNum()
10 {
11 var szText = new String(document.form1.content.value);
12 var szTextLen = szText.length;
13 if (szTextLen <= 2000)
14 show.innerHTML = "文章內容 : (目前字數 : <font color=#6575A3>" + szText.length + "</font> / 最多2000個字元)";
15 else
16 show.innerHTML = "文章內容 : (目前字數 : <font color=#B00000>" + szText.length + "</font> / <font color=#B00000>您已超過2000字元上限</font>)";
17 var timer = setTimeout("ComputeWordNum()", 250);
18 }
19 </script>
20
21 </head>
22 <body onload="ComputeWordNum()">
23 <form id="form1" runat="server">
24 <div>
25 <div id="show">
26 </div>
27 <asp:TextBox ID="content" runat="server" Height="200px" TextMode="MultiLine" Width="500px"></asp:TextBox>
28 </div>
29 </form>
30 </body>
31 </html>
32
02
03 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04 <html xmlns="http://www.w3.org/1999/xhtml">
05 <head id="Head1" runat="server">
06 <title>未命名頁面</title>
07
08 <script language="javascript" type="text/javascript">
09 function ComputeWordNum()
10 {
11 var szText = new String(document.form1.content.value);
12 var szTextLen = szText.length;
13 if (szTextLen <= 2000)
14 show.innerHTML = "文章內容 : (目前字數 : <font color=#6575A3>" + szText.length + "</font> / 最多2000個字元)";
15 else
16 show.innerHTML = "文章內容 : (目前字數 : <font color=#B00000>" + szText.length + "</font> / <font color=#B00000>您已超過2000字元上限</font>)";
17 var timer = setTimeout("ComputeWordNum()", 250);
18 }
19 </script>
20
21 </head>
22 <body onload="ComputeWordNum()">
23 <form id="form1" runat="server">
24 <div>
25 <div id="show">
26 </div>
27 <asp:TextBox ID="content" runat="server" Height="200px" TextMode="MultiLine" Width="500px"></asp:TextBox>
28 </div>
29 </form>
30 </body>
31 </html>
32
執行結果: