input 事件
IE8 及其以下不兼容
javascript
// 一般用于监听 input 和 textarea 的值的变化.
oInput.oninput = function () {
var e = e || window.event;
console.log("输入的值:" + e.target.value);
};
oInput.addEventListener(
"input",
function (e) {
var e = e || window.event;
console.log("输入的值:" + e.target.value);
},
"false"
);
changeproperty 事件
IE8 及其低版本浏览器支持, 可以替代 input 事件, 功能相似
javascript
oInput.onchangeproperty = function () {
var e = e || window.event;
console.log("值变化了:" + e.target.value);
};
oInput.addEventListener(
"changeproperty",
function (e) {
var e = e || window.event;
console.log("值变化了:" + e.target.value);
},
"false"
);
课后案例:
jd 首页搜索框效果
index.html
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>js</title>
<style>
.input-wrapper {
width: 300px;
height: 36px;
/* background: red; */
position: relative;
}
.input-wrapper .placeholder-keywords {
z-index: -1;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
padding: 0 10px;
}
.placeholder-keywords.gray {
color: #ccc !important;
}
.placeholder-keywords.black {
color: #aaa;
}
.input-wrapper .search-input {
width: 100%;
height: 100%;
border: 1px solid #eee;
box-sizing: border-box;
background-color: transparent;
padding: 0 10px;
}
</style>
</head>
<body>
<textarea style="display: none" id="keywords">["MacBookPro", "MacMini", "iphone11", "MacBookAir"]</textarea>
<div class="input-wrapper">
<div class="placeholder-keywords black"></div>
<input type="text" class="search-input" />
</div>
<script src="./js/utils.js"></script>
<script src="./js/search.js"></script>
</body>
</html>
js/search.js
javascript
window.onload = function () {
init();
};
function init() {
keySearch();
}
var keySearch = (function () {
"use strict";
var keywords = JSON.parse(_.$("keywords").value),
keywordIndex = 0,
timer = null,
placeholder = _.$findOne(".placeholder-keywords"),
searchInput = _.$findOne(".search-input");
// input
_.addEvent(searchInput, "input", function (e) {
var e = e || window.event;
placeholder.innerText = "";
});
// focus
_.addEvent(searchInput, "focus", function (e) {
var e = e || window.event;
stopTimer();
placeholder.classList.add("gray");
});
// blur
_.addEvent(searchInput, "blur", function (e) {
var e = e || window.event;
startLoopKeywordTimer();
placeholder.classList.remove("black");
});
// clear timer
function stopTimer() {
timer && clearInterval(timer);
}
// start timer
function startLoopKeywordTimer() {
var len = keywords.length - 1;
var curKeyword;
timer && clearInterval(timer);
timer = setInterval(function () {
curKeyword = keywords[keywordIndex];
console.log("curKeyword: ", curKeyword);
keywordIndex = keywordIndex >= len ? 0 : keywordIndex + 1;
placeholder.innerText = curKeyword;
}, 1000);
}
return function () {
startLoopKeywordTimer();
};
})();