這個方法很簡單,直接看示例即可。透過在 onkeyup 與 onbeforepaste 中用正規表達式過濾非中文字元,就能限制輸入框只能輸入中文。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>只能輸入中文</title>
</head>
<body>
<input type="text" id="text"
onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')"
onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\u4E00-\u9FA5]/g,''))">
</body>
</html>
關鍵在於使用 /[^\u4E00-\u9FA5]/g 這個正規表達式,把不在常用中文字元範圍內的內容都替換掉;同時在貼上時也做同樣過濾,避免使用者用貼上的方式繞過限制。