2016-08-24 101 views
0

我們知道,當用戶在某些輸入字段中輸入某個值時,我們可以從表單中獲取值,是否可以通過它從整個身體獲取值(如果用戶在身體上鍵入某個值)? 我試着在HTML頁面的body標籤添加onkeyup="behavior()"和JavaScript背後是如何獲得使用JavaScript的身體標記的價值?

function behavior() 
{ 
var key = document.body.value; 
window.alert(key); 
} 

它沒有工作,我也嘗試

var key = document.body.innerHTML; 

空話工作,我該怎麼辦呢?

感謝

+2

如何爲您的用戶能寫的東西在你的'',什麼情況? – Roberrrt

+0

@Roberrrt我的意思是當某人在我的網頁上輸入(任何地方)。 –

+0

探索你的'document.forms'集合。 'console.log(document.forms)' – Roberrrt

回答

1

這只是一個鍵盤監聽事件。

document.body.onkeyup = function(e){ 
 
    var keyCode = e.which || e.keyCode || e.charCode; 
 
    var key = String.fromCharCode(keyCode); 
 
    document.getElementById("output").innerHTML += key; 
 
}
<!DOCTYPE html> 
 
<html lang="en"> 
 
    <head></head> 
 
    <body> 
 
    This is the body's content. 
 
    <div id="output"></div> 
 
    </body> 
 
</html>

+0

,'我需要什麼。謝謝。 –

1

你可以聽上window對象keyup事件。這基本上會捕獲網頁上鍵入的每個鍵。

window.onkeyup = function(e){ 
 
    //old browsers 
 
    var keyCode = e.which || e.keyCode || e.charCode; 
 
    var key = String.fromCharCode(keyCode); 
 

 
    //modern browsers 
 
    //var key = e.key; 
 
    console.log(key); 
 
};

0

我猜你要檢查哪個鍵按下..

function keypressed(event) { 
 
    console.log(event.which); 
 
}
<body onkeyup="keypressed(event);"> 
 

 

 
</body>

爲的keyPressed的ascii碼檢查控制檯。