[英]How to get the value of a body tag using javascript?
我們知道,當用戶在某個輸入字段中輸入某個值時,我們可以從Form中獲取值;無論如何,我們是否可以從整個主體中獲取值(如果用戶在主體上鍵入內容)? 我嘗試在HTML頁面的body標簽中添加onkeyup="behavior()"
,其后的JavaScript是
function behavior()
{
var key = document.body.value;
window.alert(key);
}
它沒有用,我也嘗試過
var key = document.body.innerHTML;
什么都沒用,我該怎么辦?
謝謝
您可以在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); };
這只是一個鍵盤監聽事件。
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>
我猜您想檢查按下了哪個鍵。
function keypressed(event) { console.log(event.which); }
<body onkeyup="keypressed(event);"> </body>
檢查控制台以獲取按鍵的ascii代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.