2017-02-24 60 views
0

我想在我的浏览器中创建一个终端,但我不知道如何制作终端,以便如果我键入一个“命令”,它会响应“终端”中的一些东西。这里是我的代码:假终端浏览器 - 如何使它响应

<body> 
<div id="screen">$&gt;<input></input></div> 
<script> 
$("#screen input").focus(); 
$("#screen input").on('keydown', function(event) { 
    if(event.which === 13) {// Enter key pressed 
     var $this = $(this), 
      val = $this.val(); 
     $this.focus().val(''); 
     if(val === "hello world") { 
      //respond with something in the terminal here 
     } 
    } 
}); 
</script> 
</body> 

所以我只是想,当我做了命令的“Hello World”它这样应对的终端。

+0

你擦除值以同样的方式...'$ this.val( '您好。');'。 – Santi

+0

我希望它不在输入中,因此它不能被编辑@Santi – Gavwin

+0

Scott在回复时发布了一个很好的解决方案,请查看他的答案。 – Santi

回答

2

你需要添加一个假的“控制台”输出区域。那么,这样的事情?

FYI:$this.focus().val('');应该仅仅是:$this.val('');<input>元素没有关闭标签(</input>

// Get reference to the output area 
 
var $out = $("#output"); 
 

 
$("#screen input").focus(); 
 
$("#screen input").on('keyup', function(event) { 
 

 
    if(event.which === 13) { 
 
     // Enter key pressed 
 
     var $this = $(this); 
 
     var val = $this.val(); 
 
     
 
     if(val === "hello world") { 
 
     $out.append(">> Hello Galaxy<br>"); 
 
     } 
 
     
 
     $this.val(''); 
 
    } 
 
});
body { 
 
    font-family:"courier new", monospaced; 
 
    border-radius:5px; 
 
    border:2px solid black; 
 
    height:60vh; 
 
    background-color:rgba(200,200,200, .5); 
 
    padding:10px; 
 
} 
 

 
input { 
 
    background-color:rgb(0, 150, 0); 
 
    color: #ff0; 
 
    font-weight:bold; 
 
    letter-spacing:.2em; 
 
} 
 
#output { 
 
    color:#000; 
 
    background-color:rgba(200,200,200, .25); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="screen">$&gt;<input></div> 
 

 
<!-- This is the output area --> 
 
<div id="output"></div>

+0

谢谢!这就是我正在寻找的 – Gavwin

+0

@Gavwin增加了一些造型,只是为了好玩! –

+0

很酷,谢谢! @斯科特马库斯 – Gavwin

0

你可以通过一个字符串.val()设置输入的值:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<body> 
 
<div id="screen">$&gt;<input></input></div> 
 
<script> 
 
$("#screen input").focus(); 
 
$("#screen input").on('keydown', function(event) { 
 
    if(event.which === 13) {// Enter key pressed 
 
     var $this = $(this), 
 
      val = $this.val(); 
 
     $this.focus().val(''); 
 
     if(val === "hello world") { 
 
      $this.val('hi!') // just set the val 
 
     } 
 
    } 
 
}); 
 
</script> 
 
</body>

+0

我想让它不在输入中,因为它在外面,所以不能编辑。 – Gavwin

+0

斯科特的解决方案将工作 - 下一次明确提到你希望输出在问题中显示:) –

+0

好的,谢谢@anied – Gavwin