input点击指定区域不失焦
场景
做需求时碰到了一个问题,就是input失去焦点会触发请求接口操作,而点击旁边的按钮不触发这个操作。这个问题困扰了挺长时间,通过查阅资料找到了解决方案,记录一下。
1、在按钮点击操作时添加一个onmousedown方法,使用e.preventDefault操作,这样就阻止了input失焦点的触发,简易代码如下。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div> 1: <input type="text"> <button>我是解决1</button> </div> <script> const input = document.querySelector('input') const button = document.querySelector('button') input.onblur = () => { console.log('我是失去焦点的操作' ) } // 第一种 // 用button下的一个onmousedown 用e.preventDefault来处理 button.onmousedown = (e) =&