当<p>没有时,为什么<span>在这里工作?

时间:2017-05-15 15:39:00

标签: javascript html css

Cou请你解释一下为什么使用空元素显示“Time Taken”和秒数。如果我使用"<p id="timer">Time Taken:</p>" and no <span>,则不会显示字符串“Time Taken”

display without "Time Taken"仅显示所花费的秒数。谢谢!

  

拍摄时间:

     

    <script type="text/javascript">
        var startTime = new Date().getTime();

        function shapeAppear() { 

            document.getElementById("square").style.display = "block"; 

            startTime = new Date().getTime(); 

        }

        function shapeAppearDelay(){

            setTimeout(shapeAppear, Math.random() * 2000);

        }

            shapeAppearDelay ();  

            document.getElementById("square").onclick = function ()
               {document.getElementById("square").style.display = "none"; 

               var endTime = new Date().getTime(); 

              var timeTaken = (endTime - startTime)/(1000)%60; 
            //(1000)%60 to get seconds in minutes.  

            document.getElementById("timer").innerHTML = timeTaken; 

        shapeAppearDelay ();                                                            
        }

1 个答案:

答案 0 :(得分:1)

这是因为你用这一行彻底改变了#timer的内容:

document.getElementById("timer").innerHTML = timeTaken;

要仅附加到元素的末尾,请使用以下代码:

var element = document.getElementById("timer");
element.innerHTML = element.innerHTML + timeTaken;