2 回答

TA貢獻1812條經(jīng)驗 獲得超5個贊
我想你想要這樣的東西。
// The initial script
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var start, finish, diff;
// Adds event listeners
document.addEventListener('keydown',startTimer);
document.addEventListener('keyup',endTimer);
// Runs on keydown, simply stores a new date
function startTimer(e){
console.log('down', e)
start = new Date();
}
// Runs on keyup, stores a new date (time in milliseconds since
// epoch),
// then takes and prints the difference between the two.
function endTimer(e){
console.log('up', e)
finish = new Date();
diff = finish - start;
console.log('diff', diff)
document.querySelector('body').innerHTML = (diff);
}
</script>
</head>
<body>
</body>
</html>
問題是當你告訴endTimer寫已經(jīng)過去的時間量時:
document.write(diff)
您正在寫入文檔的根目錄而不是文檔中的元素。一旦被覆蓋,你就沒有一個 DOM 對象可以從中獲取事件。

TA貢獻1831條經(jīng)驗 獲得超4個贊
問題在于document.writeln()在事件處理程序中使用。使用console.log(),而不是修復(fù)該問題。
說明:document.write()在頁面加載后使用會清除當前文檔,并用傳遞的任何字符串替換內(nèi)容。學分
var start, finish, diff;
document.onkeydown = function(e){
start = new Date();
console.log(start);
}
document.onkeyup = function(e){
finish = new Date();
diff = finish - start;
console.log(finish);
console.log(diff);
}
<!--"Most stable" version, utilizing onkeyup/onkeydown and writeln-->
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
添加回答
舉報