按enter键显示另一段

时间:2016-10-24 13:45:37

标签: javascript html

如何进行javascript编码,当我按下“输入”输入type="text"时,它会显示另一段p

var btn = document.getElementById("key");
btn.onkeypress = function(e){
  if(e.keyCode === 13){
	  e.preventDefault();
  }
}
<input type="text" id="key" placeholder="south">

2 个答案:

答案 0 :(得分:1)

<强> Working fiddle

最好使用隐藏的class来隐藏/显示您的元素:

&#13;
&#13;
var btn = document.getElementById("key");

btn.onkeypress = function(e){

  if(e.keyCode === 13){
    e.preventDefault();
    document.getElementById("my-paragraph").classList.remove("hidden");
  }
}
&#13;
.hidden{
  display: none;
}
&#13;
<input type="text" id="key" placeholder="south">
<p id="my-paragraph" class='hidden'>Hidden paragraph</p>
&#13;
&#13;
&#13;

但您也可以使用内联样式display来显示/隐藏元素,请查看下面的基本示例。

希望这有帮助。

&#13;
&#13;
var btn = document.getElementById("key");

btn.onkeypress = function(e){

  if(e.keyCode === 13){
    e.preventDefault();
    document.getElementById("my-paragraph").style.display='block';
  }
}
&#13;
<input type="text" id="key" placeholder="south">
<p id="my-paragraph" style='display:none'>Hidden paragraph</p>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以动态创建段落并在其中添加文本:

&#13;
&#13;
var btn = document.getElementById("key");
var div = document.getElementById("paragraphs");
btn.onkeypress = function(e) {
    if (e.keyCode === 13) {
        var newParagraph = document.createElement('p');
        newParagraph.textContent = btn.value;
        div.appendChild(newParagraph);
    }
}
&#13;
<input type="text" id="key" placeholder="south">
<div id="paragraphs">

</div>
&#13;
&#13;
&#13;