代码
提交代码
<style> input {width: 200px;padding: 8px;font-size: 16px;outline: none;border: 1px dashed #4caf50;} input:focus {border: 1px solid #4caf50;} </style> <div> <input type="text"> </div> <script> var inputEle = document.querySelector('input'); var onKeyClick = function(e) { console.log(e); alert('现在输入框内容是:' + e.detail.value + ',触发的键是:' + e.detail.keyCode); }; inputEle.addEventListener('keyup', (e) => { console.log('键盘按键弹起了'); var keyClick = new CustomEvent('keyclick', { detail: { value: e.target.value, keyCode: e.keyCode, }, }); inputEle.addEventListener('keyclick', onKeyClick); inputEle.dispatchEvent(keyClick); inputEle.removeEventListener('keyclick', onKeyClick); }); </script>
运行结果