在线运行 https://jsrun.net/kSeKp

HTML

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <style>
  9. input{
  10. outline: none;
  11. border:none;
  12. box-sizing: border-box;
  13. }
  14. .input-wrap{
  15. position: relative;
  16. width: 250px;
  17. height: 35px;
  18. margin: 50px auto;
  19. }
  20. .input-wrap .auto-kw.show{
  21. display: block;
  22. color: #989898;
  23. }
  24. .input-wrap .auto-kw.hide{
  25. display: none;
  26. color: #666;
  27. }
  28. .input-wrap .auto-kw{
  29. position: absolute;
  30. top: 8px;
  31. left: 5px;
  32. font-size: 14px;
  33. color: #989898;
  34. z-index: -1;
  35. }
  36. .input-wrap .search-input{
  37. width: 100%;
  38. height: 100%;
  39. background-color: transparent;
  40. border: 1px solid #ddd;
  41. text-indent: 5px;
  42. color: #424242;
  43. }
  44. </style>
  45. </head>
  46. <body>
  47. <div class="input-wrap">
  48. <div class="auto-kw" id="J_autoKw">推荐词</div>
  49. <input type="text" id="J_search_kw" class="search-input" />
  50. </div>
  51. <div style="display: none;" id="J_recomkw">["美白独立日","LG显示器","洗发水套装","电脑主机","笔记本内存条"]</div>
  52. <script src="js/untils.js"></script>
  53. <script src="./js/search.js"></script>
  54. </body>
  55. </html>

JS

window.onload = function(){
    init();
}

function init(){
    keySearch();
}
var keySearch = (function(){
    var searchKw = document.getElementById('J_search_kw'),
        autoKw = document.getElementById('J_autoKw'),
        recomKw = JSON.parse(document.getElementById('J_recomkw').innerHTML),
        kwOrder = 0,
        t = null;


    addEvent(searchKw,'focus',function(){
        clearInterval(t);
        autoKw.style.color = '#ccc';
    });

    addEvent(searchKw,'blur',function(){
        autoKwShow(this.value,true);
        t = setInterval(autoKwChange,3000);
    })

    addEvent(searchKw,'input',function(){
        autoKwShow(this.value,false);
    })

    addEvent(searchKw,'propertychange',function(){
        autoKwShow(this.value,false);
    })

    function setAutoKws(){
        autoKwChange();
        console.log(recomKw[kwOrder]);
        t = setInterval(autoKwChange,3000);
    }



    function autoKwChange(){

        var len = recomKw.length;
        // console.log(recomKw[kwOrder]);
        autoKw.innerHTML = recomKw[kwOrder];

        kwOrder = kwOrder >= len - 1? 0: kwOrder+1;
    }

    function autoKwShow(val,isBlur){
        if(val.length<=0){
            autoKw.className = 'auto-kw show';
            autoKw.style.color = isBlur ? '#989898' : '#ccc';
        }else{
            autoKw.className = 'auto-kw hide'
        }
    }
    return function(){
        setAutoKws();
    }
})();