<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="http://libs.baidu.com/jquery/1.8.3/jquery.min.js"></script>
<title></title>
</head>
<body>
<input id="txt" type="text">
<script>
var flag = true;
$('#txt').on('compositionstart',function(){
flag = false;
})
$('#txt').on('compositionend',function(){
flag = true;
})
$('#txt').on('input',function(){
var _this = this;
setTimeout(function(){
if(flag){
console.log($(_this).val());
}
},0)
})
</script>
</body>
</html>
(compositionstart compositionend)
https://www.cnblogs.com/lonhon/p/7643095.html
事件列表
https://developer.mozilla.org/zh-CN/docs/Web/Events
百度搜索框自动联想下拉菜单的实现思路
var tid = 0;
var upId = 0;
function handler() {
if (tid != 0) {
clearTimeout(tid);
tid = 0;
}
tid = setTimeout(function() {
var currentId = upId = new Date().getTime();
tid = 0;
发请求(function(res) {
if (currentId != upId) {
return;
}
updateView();
});
}, 300);
}
第一次发:
currentId(1) = upId = 1;
第二次:
currentId(2) = upId = 2;
第一次请求回来:
发现currentId = 1, upId = 2 抛弃
第二次:
currentId = 2, upId = 2 使用这个
输入框根据输入不断发请求的逻辑代码:
1、连续输出的时候,只对用户停下来时的输入文本做查询请求(使用timeout来控制)
2、请求一半,又有新的请求,那么以后边的为准。(currentId和upId一致才认,不一致,认为是旧请求,抛弃,注意二者的作用域)
上面是个人实现方法,下面采用一些插件
https://lodash.com/docs#debounce ( 请参考:文档)
// `_.debounce` 是一个通过 Lodash 限制操作频率的函数。
// 在这个例子中,我们希望限制访问 url/api 的频率
// AJAX 请求直到用户输入完毕才会发出。想要了解更多关于
// `_.debounce` 函数 (及其近亲 `_.throttle`) 的知识,
demo:
getAnswer: _.debounce(
function () {
if (this.question.indexOf('?') === -1) {
this.answer = 'Questions usually contain a question mark. ;-)'
return
}
this.answer = 'Thinking...'
var vm = this
axios.get('url/api')
.then(function (response) {
vm.answer = _.capitalize(response.data.answer)
})
.catch(function (error) {
vm.answer = 'Error! Could not reach the API. ' + error
})
},
// 这是我们为判定用户停止输入等待的毫秒数
500
)
在新浏览器中可以使用的黑科技:observe
<textarea id="text"></textarea>
<script type="text/javascript">
var mObserv = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
var text = document.getElementById("text");
var observ = new mObserv(function(ev) {
console.log(ev);
});
observ.observe(text, {
attributes: true,
childList: false,
characterData: false,
});
setTimeout(function() {
text.style.color = "red";
}, 2000);
</script>
可以监听节点的参数值、子节点列表、数据是否发生变化,并在发生变化的时候处理
这是监听DOM对象的,同时,JS对象同样可以使用Object.observe()去监听。当属性值发生变化的时候会来通知你,调用你的回调
http://www.tuicool.com/articles/AFVzmiz