2017-02-24 12 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