我正在尝试测量盒子分离和用户点击盒子的时间之间的时间,所以我做了这个:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>JavaScript</title>
<style type="text/css">
body{
background: gray;
}
#box{
width: 100px;
height: 100px;
background: red;
visibility: "hidden";
}
</style>
<script type="text/javascript">
window.onload = function(){
var clickedTime; //to store the time when the box is clicked
var createdTime; //to store the time when the box is created
var reactionTime; //secs between the box creation and box click
function appear(){
//this function is to make the box appear
setTimeout(function(){
document.getElementById("box").style.visibility = "visible";
createdTime = Date.now();
console.log("createdTime: "+createdTime);
}, Math.random()*5000);
}
document.getElementById("box").onclick = function(){
//this is to hide the box, make it appear and calculate the reaction time
clickedTime = Date.now();
console.log("clickedTime: "+clickedTime);
reactionTime = (clickedTime - createdTime)/1000;
console.log("reactionTime: "+reactionTime);
alert(reactionTime);
this.style.visibility = "hidden";
appear();
}
appear();
}
</script>
</head>
<body>
<div id="box"></div>
</body>
</html>
当用户一开始快速单击该框时,就会出现问题,此时会显示 NaN 的警报,并且控制台日志显示:
- 点击时间:1428200428320
- react 时间:NaN
通过简单观察,此时createdTime变量中没有任何内容,即使在调用函数appear()时将框设置为可见,并且该函数还为变量createdTime赋值。还有一点是,即使我设置了超时,该框显示的速度也非常快,该框应该在随机延迟后出现。
我的代码连续第二次运行得很好。 我的问题是如何避免/解决这种现象?我做错了什么?
感谢您的关注
最佳答案
在 CSS 中,更改以下内容:
visibility: "hidden";
…对此:
visibility: hidden;
否则,元素开始时可见,因此 createdTime
可能尚未在第一次单击时初始化。
片段:
window.onload = function() {
var clickedTime; //to store the time when the box is clicked
var createdTime; //to store the time when the box is created
var reactionTime; //secs between the box creation and box click
function appear() {
//this function is to make the box appear
setTimeout(function() {
document.getElementById("box").style.visibility = "visible";
createdTime = Date.now();
console.log("createdTime: " + createdTime);
}, Math.random() * 5000);
}
document.getElementById("box").onclick = function() {
//this is to hide the box, make it appear and calculate the reaction time
clickedTime = Date.now();
console.log("clickedTime: " + clickedTime);
reactionTime = (clickedTime - createdTime) / 1000;
console.log("reactionTime: " + reactionTime);
alert(reactionTime);
this.style.visibility = "hidden";
appear();
}
appear();
}
body {
background: gray;
}
#box {
width: 100px;
height: 100px;
background: red;
visibility: hidden;
}
<div id="box"></div>
关于javascript - 在 JavaScript 中如何修复元素显示和变量创建之间的初始差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29453653/