例如我们在输入框输入文字时,如何监听input输入框内容的变化,然后根据内容的变化,我们去触发相应的事件。这个时候我们就应该给输入框input绑定三个事件,keypress,keydown,keyup。下面我将写一个demo来模仿搜索输入框中的差号的显示与隐藏。
style部分
body{
width: 100%;
height: 100%;
}
.input{
position: relative;
width: 300px;
height: 30px;
}
input{
width: 300px;
height: 30px;
border: none;
outline: none;
-webkit-appearance: none;
border: 1px solid red;
}
.cicle{
display: inline-block;
width: 20px;
height: 20px;
background: black;
border-radius: 10px;
position: absolute;
right: 10px;
top: 5px;
display: none;
}
html部分
<div class="input">
<input name="" rows="" cols="" id="text-area"placeholder="请输入文字"></input>
<span class="cicle"></span>
</div>
script部分
js原生绑定事件
window.onload = function() {
document.getElementById("text-area").addEventListener('keypress', function() {
calfontCount();
}, false);
document.getElementById("text-area").addEventListener('keydown', function() {
calfontCount();
}, false);
document.getElementById("text-area").addEventListener('keyup', function() {
calfontCount();
}, false);
}
jq写法
$(function() {
$("#text-area").bind("keypress", function() {
calfontCount();
});
$("#text-area").bind("keydown", function() {
calfontCount();
});
$("#text-area").bind("keyup", function() {
calfontCount();
});
})
用到的方法
function calfontCount() {
var textSpan = document.getElementById("textSpan");
var textArea = document.getElementById("text-area");
var cur = textArea.value.replace(/\s/g, '').length; //当前文字个数
if(cur > 0) {
$(".cicle").show();
} else {
$(".cicle").hide();
}
}
效果展示
