防抖案例實戰之仿百度搜索框即時搜索


百度搜索框交互體驗是當用戶輸入完成后一定時間后才發起搜索請求,所以我們設計的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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM