限制文本框只能输入数值
var inputNum = document.getElementById("inputNum"); if(inputNum.addEventListener) { inputNum.addEventListener("paste", pasteEvent); inputNum.addEventListener("keypress", keypressEvent); } else { inputNum.attachEvent("onpaste",pasteEvent); inputNum.attachEvent("onkeypress", keypressEvent); }
function pasteEvent(e) { var pastedText = ""; var element = e.target||e.srcElement; if(window.clipboardData && window.clipboardData.getData) { // IE pastedText = window.clipboardData.getData('Text'); } else { pastedText = e.clipboardData.getData('text/plain'); } element.setAttribute("maxlength", element.value.length); if(/^[0-9\.e\-]+$/.test(pastedText)) { element.setAttribute("maxlength", pastedText.length + element.value.length); } }
function keypressEvent(e) { e = e || window.event; var element = e.target||e.srcElement; //获取键对应的符号(兼容IE8,FF,Chrome) var ekey = e.key || String.fromCharCode(e.keyCode || e.charCode); if(/^[0-9\.e\-]+$/.test(ekey)) { element.setAttribute("maxlength", element.value.length + 1); } else { element.setAttribute("maxlength", 0); } }