百度搜索框交互體驗是當用戶輸入完成后一定時間后才發起搜索請求,所以我們設計的input回調應該包含一個定時器,當在規定時間內沒有input才能執行處理邏輯(專業術語叫做防抖),規定時間內觸發input事件就重置定時器。見下例:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <link rel="stylesheet" href=""> </head> <body> <input type="text" name="" id="input"> <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script> <script type="text/javascript"> let debounce = (func, wait=500) => {//利用防抖實現 let timer = null; return function(...args) { if(timer) clearTimeout(timer) timer = setTimeout( () => { func.apply(this,...args) },wait) } } $('input[type=text]').on('input',debounce(function(){ console.log(this.value) let value = this.value; //$.ajax({})發送請求 },700)) </script> </body> </html>