oninput出自于HTML5的规范里面,IE9某些版本及IE9以下使用的是onpropertychange
在写鼠标输入事件的时候考虑到兼容性要两个都写
onchange失去焦点才会触发
由于placeholder不好修改,不容易自定义,所以一般用focus和blur来实现placeholder
onfocus onblur
<input type="text"
class="inp"
οnfοcus="if(this.value === '请输入关键字'){
this.value = '';
this.className = '';
}"
οnblur="if(this.value === ''){
this.value = '请输入关键字';
this.className = 'inp';
}"
模拟京东搜索框
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.wrap {
position: relative;
width: 400px;
height: 200px;
margin: 50px auto;
border: 1px solid #000;
}
.ph-box {
position: absolute;
left: 50px;
top: 50px;
width: 300px;
height: 38px;
line-height: 38px;
color: #989898;
}
.ph-box.show{
display: block;
}
.ph-box.hide{
display: none;
}
input {
position: absolute;
left: 50px;
top: 50px;
width: 300px;
height: 38px;
outline: none;
border: 1px solid #baf;
background-color: transparent;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="wrap">
<div class="ph-box">111</div>
<input type="text"
id="J-search_kw"
class="search-input"
/>
<div style="display: none" class="show-content">
["湿纸巾","存储卡","洗衣机","手机","电脑"]
</div>
</div>
<script type="text/javascript">
<!-- 模拟京东搜索框 -->
window.onload = function(){
init();
}
function init(){
searchKeyword();
}
var searchKeyword = (function(){
var content = document.getElementsByClassName('search-input')[0],
autoKey = document.getElementsByClassName('ph-box')[0],
keywords =JSON.parse(document.getElementsByClassName('show-content')[0].innerText),
t = null,
keyOrder = 0;
function setKeyword(){
autoKey.innerHTML = keywords[keyOrder];
t = setInterval(autoKws, 1000)
}
addEvent(content, 'input', function(e){
showAutoKws(this.value);
})
addEvent(content, 'propertyChange', function(e){
showAutoKws(this.value);
})
addEvent(content, 'blur', function(e){
showAutoKws(this.value, true);
})
addEvent(content, 'focus', function(e){
clearInterval(t);
})
function autoKws(){
var len = keywords.length;
autoKey.innerHTML = keywords[keyOrder];
keyOrder = keyOrder < len - 1 ? keyOrder + 1 : 0;
}
function showAutoKws(val, isBlur){
if(val.length <= 0){
autoKey.className = 'ph-box show';
if(isBlur) {
t = setInterval(autoKws, 1000);
}
} else {
autoKey.className = 'ph-box hide';
}
}
return function(){
setKeyword();
}
})();
function addEvent(ele, type, fn){
if(ele.addEventListener){
ele.addEventListener(type, fn, false);
} else if(ele.attachEvent){
ele.attachEvent('on' + type, fn);
} else {
ele['on' + type] = fn;
}
}
</script>
</body>
</html>