1.
https://www.baidu.com/link?url=09OJjzJi-wmdSLeX-TwOFH5P_kSzGhurmkm7j-xzv6Prdde7tVLPU_drx9Zw2_bYHzJ6NDGPikTySw35ojSXdcCyUf49vXsxG-1EsPpocpi&wd=&eqid=efa9959700010edf000000035b627191
2.
这个效果是输入内容后,输入数字或者英文字母触发事件,获取输入字符个数
用搜索等输入法时输入内容最后按确定按钮才会触发事件,获取输入字符个数
3.
react文件:
import React, { Component } from 'react';
import './index.less'
class Rank extends Component {
constructor(props){
super(props)
this.state={
newdivhanzi:false,
newdivlength:0,
}
}
componentDidMount(){
}
divcompositionstart(e){
console.log(1)
//console.log(e)
//e.target.innerText = e.target.innerText
if(this.state.newdivhanzi===false){
this.setState({
newdivhanzi:true
})
}
}
divcompositionend(e){
if(this.state.newdivhanzi===true){
if(e.target.innerText.length>=5){
e.target.innerText = e.target.innerText.substring(0,5)
this.setState({
newdivlength:5,
newdivhanzi:false
})
this.newkeepLastIndex();
}else{
this.setState({
newdivlength:e.target.innerText.length,
newdivhanzi:false
})
}
}
}
newdivonkeydown(e){
if(this.state.newdivhanzi===false){
if(e.target.innerText.length>=5){
console.log(e.target.innerText.length)
e.target.innerText = e.target.innerText.substring(0,5)
this.newkeepLastIndex();
}
}
}
newdivonkeyup(e){
if(this.state.newdivhanzi===false){
if(e.target.innerText.length>=5){
e.target.innerText = e.target.innerText.substring(0,5)
this.newkeepLastIndex();
this.setState({
newdivlength:e.target.innerText.length
})
}else{
this.setState({
newdivlength:e.target.innerText.length
})
}
}
}
newkeepLastIndex() {
if (window.getSelection) {//ie11 10 9 ff safari
this.refs.divrefref.focus(); //解决ff不获取焦点无法定位问题
var range = window.getSelection();//创建range
range.selectAllChildren(this.refs.divrefref);//range 选择obj下所有子内容
range.collapseToEnd();//光标移至最后
}
else if (document.selection) {//ie10 9 8 7 6 5
var range = document.selection.createRange();//创建选择对象
//var range = document.body.createTextRange();
range.moveToElementText(this.refs.divrefref);//range定位到obj
range.collapse(false);//光标移至最后
range.select();
}
}
render() {
return (
<div className="wrap_app">
{this.state.newdivlength}/5
<div ref="divrefref"
onCompositionStart={(e)=>this.divcompositionstart(e)}
onCompositionEnd={(e)=>this.divcompositionend(e)}
onKeyUp={(e)=>this.newdivonkeyup(e)}
onKeyDown={(e)=>this.newdivonkeydown(e)}
contentEditable="true" className="divinit"></div>
</div>
);
}
}
export default Rank
4.
less文件:
@import '../../assets/css/common.less';
.divinit{
.w(750);
.fs(30);
min-height: 100/75*1rem;
max-height: 200/75*1rem;
background: green;
overflow-y: auto;
}