当我按下逃生时如何按空格键

时间:2015-08-04 10:43:36

标签: javascript html textarea onkeypress

以下示例中,如何按"空格键按下"当我按下回车键时动作?
我想要的是当我按下回车键时,它会添加一个空格,就像我按下空格键一样。



var textarea = document.getElementById("textarea");

textarea.onkeypress = function(){return (event.charCode >= 48 && event.charCode <= 57)||(event.charCode == 32);};
&#13;
textarea{
  height : 100px;
  width : 500px;
}
&#13;
<textarea id="textarea" placeholder="Here you can only press numbers and space bar !"></textarea>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

将此添加到您的代码中:

if(event.charCode == 13){
        textarea.value = textarea.value + " ";
}

完整代码:

var textarea = document.getElementById("textarea");

textarea.onkeypress = function (event) {
    if(event.charCode == 13){
        textarea.value = textarea.value + " ";
    }
    return (event.charCode >= 48 && event.charCode <= 57) || (event.charCode == 32);
};

Here is the JSFiddle demo

答案 1 :(得分:0)

var textarea = document.getElementById("textarea");

textarea.onkeypress = function(event){
	 var code = (event.keyCode ? event.keyCode : event.which);
	 if(!(code == 13 || code == 32 || code == 8 || code == 46 || (code>= 48 && code <= 57))){
	 	 event.preventDefault();
	 	
	 }
	
};
textarea{
  height : 100px;
  width : 500px;
}
<textarea id="textarea" placeholder="Here you can only press numbers and space bar !"></textarea>