一个简单的JavaScript不工作

时间:2015-10-04 16:14:04

标签: javascript

我想衡量用户保持网站焦点的时间,但它不起作用。

<!doctype html>
<head>

<script>
    var timeActive;
    function timeActiveFuncStart(){
        timeActive = 0;
        function timeActiveFunc(){
            timeActive++;
            setTimeout("timeActiveFunc()", 1000)}}

    var timeActiveTotal;
    function timeActiveTotalFunc(){
        timeActiveTotal = timeActiveTotal + timeActive}

    document.getElementById("timeActiveP").innerHTML = timeActive;
    document.getElementById("timeActiveTotalP").innerHTML = timeActiveTotal;
</script>

</head>

<body onfocus="timeActiveFuncStart()" onblur="timeActiveTotalFunc()">

<p id="timeActiveP"></p>
<p id="timeActiveTotalP"></p>

</body>
</html>

2 个答案:

答案 0 :(得分:4)

这是因为,JavaScript无法访问这些元素。另外,请考虑以这种方式使用setInterval而不是setTimeout

请将<script>替换为底部:

<!doctype html>
<head>

</head>

<body onfocus="timeActiveFuncStart()" onblur="timeActiveTotalFunc()">

  <p id="timeActiveP"></p>
  <p id="timeActiveTotalP"></p>

  <script>
    var timeActive;
    var timeActiveTotal = 0;
    function timeActiveTotalFunc() {
      timeActiveTotal = timeActiveTotal + timeActive;
    }
    function timeActiveFuncStart() {
      timeActive = 0;
      function timeActiveFunc() {
        timeActive++;
        document.getElementById("timeActiveP").innerHTML = timeActive;
        document.getElementById("timeActiveTotalP").innerHTML = timeActiveTotal;

      }
      setInterval(timeActiveFunc, 1000);
    }

  </script>

</body>
</html>

或者,你可以在window.onload事件之后把它放进去吗?

<!doctype html>
<head>

<script>
  window.onload = function () {
    var timeActive;
    function timeActiveFuncStart(){
        timeActive = 0;
        function timeActiveFunc(){
            timeActive++;
        }
        setInterval("timeActiveFunc()", 1000);

    var timeActiveTotal;
    function timeActiveTotalFunc(){
        timeActiveTotal = timeActiveTotal + timeActive}

    document.getElementById("timeActiveP").innerHTML = timeActive;
    document.getElementById("timeActiveTotalP").innerHTML = timeActiveTotal;
  }
</script>

</head>

<body onfocus="timeActiveFuncStart()" onblur="timeActiveTotalFunc()">

<p id="timeActiveP"></p>
<p id="timeActiveTotalP"></p>

</body>
</html>

答案 1 :(得分:0)

再次感谢您的帮助,但是......这里终于有了作用:

<script>
var timeActive = 0;
var timeActiveTotal = 0;

window.onpageshow = function(){
    setInterval(function(){
        timeActive++;
        document.getElementById("timeActiveP").innerHTML = timeActive;
    }, 1000);

    window.onblur = function(){
        timeActiveTotal = timeActiveTotal + timeActive;
        document.getElementById("timeActiveTotalP").innerHTML = timeActiveTotal;
    }

    window.onfocus = function(){
        timeActive = 0;
    }
}
</script>