index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
input {
outline: none;
border: none;
box-sizing: border-box;
}
.input-wrap {
position: relative;
width: 250px;
height: 35px;
margin: 50px auto;
}
.auto-kw {
position: absolute;
left: 5px;
top: 8px;
font-size: 14px;
color: #989898;
z-index: -1;
}
.auto-kw.show {
display: block;
color: #989898;
}
.auto-kw.hide {
display: none;
color: #666;
}
.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="recomKw">
["美白独立日","LG显示器","洗发水套装","电脑主机","笔记本内存条"]
</div>
<script src="js/utils.js"></script>
<script src="js/index.js"></script>
<script>
</script>
</body>
</html>
index.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('recomKw').innerHTML),
kwOrder = 0,
t = null;
addEvent(searchKw, 'focus', function () {
clearInterval(t);
autoKw.style.color = '#ccc';
})
addEvent(searchKw, 'blur', function () {
// autoKw.style.color = '#989898';
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();
t = setInterval(autoKwChange, 3000);
}
function autoKwChange() {
var len = recomKw.length;
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()
}
})();