2 回答
TA贡献1812条经验 获得超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写已经过去的时间量时:
document.write(diff)
您正在写入文档的根目录而不是文档中的元素。一旦被覆盖,你就没有一个 DOM 对象可以从中获取事件。
TA贡献1831条经验 获得超4个赞
问题在于document.writeln()在事件处理程序中使用。使用console.log(),而不是修复该问题。
说明:document.write()在页面加载后使用会清除当前文档,并用传递的任何字符串替换内容。学分
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>
添加回答
举报