需求:
在一些查询input输入时,用户可能会从某个地方复制查询数据,然后粘贴到查询表单中,这时可能会造成复制的数据有空格,而恰巧你点表单又进行了位数设置,则复制出来的数据可能会因此少一位。
我的解决方案:
监听粘贴动作,在粘贴前把剪切板里的数据进行去空格处理,然后将处理好的数据添加到input文本框内。
示例代码:
<html>
<head>
<title>粘贴监听测试</title>
<style>
DIV#editable {
width: 400px;
height: 300px;
border: 1px dashed blue;
}
</style>
<script type="text/javascript">
window.onload=function() {
//粘贴监听,删除剪切板的空格后进行粘贴
function paste_text(e) {
debugger;
if ( e.clipboardData.items ) {
ele = e.clipboardData.items
//判断剪切板内复制的是文本
alert("type:"+ele[0].type+",kind:"+ele[0].kind);
if(ele[0].type=='text/plain' && ele[0].kind=='string'){
var text = e.clipboardData.getData('Text');
alert("剪切板内容:"+text);
//去空格并截取前11位赋值到input中
document.getElementById('q_phone').value=text.trim().substring(0,11);
}
} else {
alert('non-chrome');
}
}
document.getElementById('q_phone').onpaste=function(){paste_text(event);return false;};
}
</script>
</head>
<body >
<input id="q_phone" type="text" class="form-control input-sm" placeholder="粘贴监听区域" maxlength="11">
</body>
</html>