2016-08-24 55 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码检查控制台。