功能要求:光标在第一次进来时锁定会员码框,一定时间内页面没有操作(滚动,鼠标点击,键盘点击)的时候锁定条形码框
componentDidMount(){ // 获取焦点 const input1=document.getElementById('getInput1') const input2=document.getElementById('getInput2') const vipValue=this.state.vipInput.current.value // 自动聚焦会员码 if (vipValue==='' && this.state.inputStatus===true) { // console.log('获取焦点',this.state.vipInput); input1.focus() // this.setState({inputStatus:false}) } // 开启定时器和监听 this.timer(input1,input2,3000) } // 定义一个定时器监听方法 timer = (input1,input2,time)=> { zTimer = setInterval(() => { input1.blur() input2.focus() // 执行清除定时器方法 this.ClearTime(zTimer) }, time); // 推荐下面的监听方法,可以做到防抖,也可以正确移除监听事件。 window.addEventListener('click', this.handleDo2); window.addEventListener('keydown', this.handleDo2); window.addEventListener('mousemove', this.handleDo2); window.addEventListener('mousewheel', this.handleDo2); } // 用户操作 handleDo=(params)=>{ // 用户操作了页面,初始化用户未操作页面时长,重新开始计时。 console.log('监测操作') // 清除定时器 this.ClearTime(zTimer) // 执行条形码失去焦点事件,建立新的计时器 this.handleDome() } /** * * @param func 一段时间后用户未进行操作执行的函数 * @param wait 表示时间段,比如5000,在5秒内执行了函数则从第一秒开始 * @param flag flag 为true时表示第一次进入就执行的函数 * @returns */ debounce = (func, wait, flag) => { let timer, args, that; return function () { //args包含了func的事件对象,that为func的this指向(应当指向事件源) args = arguments; that = this; let callnow = flag && !timer; if (callnow) func.apply(that, args); //不传入参数flag这段行代码不执行 clearTimeout(timer); timer = setTimeout(function () { timer = null; if (!flag){ console.log(timer); func.apply(that, args) } }, wait); }; } // 将debounce(handleDo, 1000)返回的匿名函数赋值给handleDo2 handleDo2 =this.debounce(this.handleDo, 500,true); //第三个参数可选,需要传值时可以放入一个对象中传递参数 /** * 执行清除定时器事件并销毁监听 * @param zTimer 定义的定时器 */ ClearTime(zTimer){ console.log(zTimer, '执行清除定时器'); clearInterval(zTimer) // 销毁事件 window.removeEventListener('click', this.handleDo2); window.removeEventListener('keydown', this.handleDo2); window.removeEventListener('mousemove', this.handleDo2); window.removeEventListener('mousewheel', this.handleDo2); } componentWillUnmount(){ // 销毁事件 window.removeEventListener('click', this.handleDo2); window.removeEventListener('keydown', this.handleDo2); window.removeEventListener('mousemove', this.handleDo2); window.removeEventListener('mousewheel', this.handleDo2); } /* 聚焦条形码执行的方法,失去焦点后,开启监听,若一定 时间段内未操作,获取焦点 */ handleDome = ()=> { const input1=document.getElementById('getInput1') const input2=document.getElementById('getInput2') this.timer(input1,input2,3000) }