写了一个小页面,用来记录TEXTAREA输入的中文内容,同时记录输入时间。存入数组,最终在另一个页面以时间顺序播放文字。
timeTable是一维数组,里面的数据为【当前字数,当前时间,当前字数,当前时间……】,每次输入中文时会取当前输入字数与时间,PUSH进数组。
<textarea id=myContent rows=8 oninput="wordCheck()" textIndent=2em></textarea>
function wordCheck(){
var cursortPosition=$("#myContent").get(0).selectionStart;
var nowCount= $("#myContent").val().length;
var nowContent=$("#myContent").val()
var nowInput = nowContent[nowCount-1]
var re=/^[\u4E00-\u9FA5|\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5|\u007e]+$/
console.log("当前输入: "+nowInput,"上一个字:"+previousWord," 字数: "+nowCount,"光标位置: "+cursortPosition)
if(nowCount>theBiggest){
theBiggest=nowCount
}
//加一个最大值,为了区分输入一个中文,与删除中文前的英文
//这个判断可以继续完善,因为可以检测当前光标,就可以判断光标左右是否有字,来确定是否插入。
if(nowCount-previousCount==-1){
if (re.test(nowInput)) {
if(re.test(previousWord)){
console.log("删除中文")
}
else if(!re.test(pPreviousWord)){
if(nowCount+1==theBiggest){
console.log("输入了一个中文")
var timeArray = [nowCount,str.substring(0,str.indexOf(".") + 2)]
timeTable.push(timeArray)
}
else{
console.log("删除中文前面的符号或英文",previousWord)
}
}
else{
console.log("删除了中文前的一个东西",previousWord)
}
}
else{
console.log("删除英文")
}
}
else if(nowCount-previousCount<-1){
if (re.test(nowInput)) {
console.log("连拼输入")
var timeArray = [nowCount,str.substring(0,str.indexOf(".") + 2)]
timeTable.push(timeArray)
}
}
else{
if (re.test(nowInput)) {
console.log("中文输入")
var timeArray = [nowCount,str.substring(0,str.indexOf(".") + 2)]
timeTable.push(timeArray)
}
else{
console.log("英文输入")
}
}
previousCount=nowCount;
pPreviousWord=previousWord;
previousWord=nowInput;
}
而且同样是CHROME,高的版本与低版本对于拼音的识别不同,低版本在TEXTAREA中输入拼音时,不会触发oninput,只有完成汉字选择,输入后,才触发。
而高版本的CHROME,在输入拼音时,未进行选字,就已经触发了ONINPUT。
这才是这个复杂判断的由来。如果TEXTAREA可以区分拼音与英文的输入,就没这么麻烦了。
已将完整DEMO上传至github: https://github.com/HTML50/listen2me