想要在点击按钮和单击div之间显示时间

时间:2015-02-13 22:31:11

标签: javascript timer

您好,感谢您阅读本文。任何帮助是极大的赞赏。我正在尝试创建一个函数,当按下按钮触发时,启动计时器,然后在随机位置显示div。单击div时,JavaScript会记录按下按钮和单击div之间的时间并将其返回到段落中。我让广场工作,但计时器不起作用,并影响我的其余代码的性能。这是我到目前为止所拥有的。

HTML:

<body>
    <p id="TotalTime"> </p>
    <button id="funbutton" onclick="SeeWhatHappens(funbutton)">Click here!</button>
    <div id="newdiv" class="a"></div>
</body>

JavaScript的:

function SeeWhatHappens(button) {
    var startTime = new Date();
    var divsize = 50;
    var posx = (Math.random() * window.innerWidth - divsize).toFixed();
    var posy = (Math.random() * window.innerHeight - divsize).toFixed();
    var div = document.getElementById('newdiv');
    div.style.left = posx + 'px';
    div.style.top = posy + 'px';
    div.style.display = 'block';
    button.style.visibility = "hidden";
    var something = document.getElementById('newdiv');
    something.style.cursor = 'pointer';
    something.onclick = GetTime(startTime) {

}

function GetTime(startTime){
var endTime = new Date();
var timeDiff = endTime - startTime;
var timeDiff /= 1000;
var seconds = Math.round(timeDiff % 60);
timeDiff = Math.floor(timeDiff / 60);
var minutes = Math.round(timeDiff % 60);
timeDiff = Math.floor(timeDiff / 60);
var hours = Math.round(timeDiff % 24);
timeDiff = Math.floor(timeDiff / 24);
document.getElementByID('TotalTime') = timeDiff;
}

编辑:这是我的JSFiddle以防万一:

http://jsfiddle.net/6hnLx6qc/17/

再次感谢你们给我的任何帮助!

1 个答案:

答案 0 :(得分:1)

这是一个工作版本:

var button = document.getElementById('funbutton');
button.addEventListener('click', SeeWhatHappens);

function SeeWhatHappens() {
    var startTime = new Date();
    var divsize = 50;
    var posx = (Math.random() * window.innerWidth - divsize).toFixed();
    var posy = (Math.random() * window.innerHeight - divsize).toFixed();
    var div = document.getElementById('newdiv');
    div.style.left = posx + 'px';
    div.style.top = posy + 'px';
    div.style.display = 'block';
    button.style.visibility = "hidden";
    var something = document.getElementById('newdiv');
    something.style.cursor = 'pointer';
    something.onclick = function() {GetTime(startTime);};
}

function GetTime(startTime){
var endTime = new Date();
var timeDiff = endTime - startTime;

var timeDiff = timeDiff / 1000;
document.getElementById('TotalTime').innerHTML = timeDiff;
}

http://jsfiddle.net/6x4ho4ga/1/