需求:頁面上有input和select等輸入框和下拉框,回車相互切換
實現:
html:
<div className="input-container"> <div> <Input /> <Input /> </div> <div> <select> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="opel">Opel</option> <option value="audi">Audi</option> </select> </div> </div>
javascript核心功能:
function changeEnter(inputs) { const init = () => { for(let i = 0; i < inputs.length; i++) { inputs[i].addEventListener('keydown', focus(i), false); // 每個input添加鍵盤監聽 } } const focus = (i) => { return (event) => { const next = i + 1 < inputs.length ? i + 1 : 0; // 判斷是否為最后一個輸入框,是則返回第一個,否則繼續下一個 const eve = event ? event : window.event; if (eve.keyCode === 13) { if (inputs[next].tagName === 'INPUT' || inputs[next].tagName === 'SELECT') { inputs[next].focus(); } } } } const destory = () => { for(let i = 0; i < inputs.length; i++) { inputs[i].removeEventListener('keydown', focus(i), false); // 解除監聽 } } init(); return { destory() { destory(); } } }
代碼調用:
componentDidMount() { // 獲取頁面上input和select的dom元素 const changes = document.querySelectorAll('.input-container input, select'); this.inputEnter = changeEnter(changes); } componentWillUnmount() { // 卸載解除監聽事件 this.inputEnter.destory(); }
實現效果:
備注:如果是Ant的Select組件,要換種寫法,可以用官方文檔上寫的onInputKeyDown(按下回車時的回調)實現,寫法稍有不同,但實現邏輯差不多。