在线运行 https://jsrun.net/kSeKp
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> input{ outline: none; border:none; box-sizing: border-box; } .input-wrap{ position: relative; width: 250px; height: 35px; margin: 50px auto; } .input-wrap .auto-kw.show{ display: block; color: #989898; } .input-wrap .auto-kw.hide{ display: none; color: #666; } .input-wrap .auto-kw{ position: absolute; top: 8px; left: 5px; font-size: 14px; color: #989898; z-index: -1; } .input-wrap .search-input{ width: 100%; height: 100%; background-color: transparent; border: 1px solid #ddd; text-indent: 5px; color: #424242; } </style></head><body> <div class="input-wrap"> <div class="auto-kw" id="J_autoKw">推荐词</div> <input type="text" id="J_search_kw" class="search-input" /> </div> <div style="display: none;" id="J_recomkw">["美白独立日","LG显示器","洗发水套装","电脑主机","笔记本内存条"]</div> <script src="js/untils.js"></script> <script src="./js/search.js"></script></body></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();
}
})();