我想在頁面加載時開始的頁面上添加一個計時器。
它以毫秒為單位上升。
然后當滑鼠點擊按鈕時停止。
我將如何創建一個代碼示例?
這就是我想要在代碼中做的所有事情。
添加一個在頁面加載時啟動的計時器。
以毫秒為單位上升。
然后在單擊按鈕時停止。
我希望能夠看到數字上升。
https://jsfiddle.net/xvkwmndq/
// Counter
var enterDate = new Date();
function secondsSinceEnter()
{
return (new Date() - enterDate) / 1000;
}
// Usage example
document.querySelector('button').onclick = function() {
var sec = secondsSinceEnter();
if (sec < 10)
this.innerText = sec " seconds";
else
this.innerText = 'You are here like for eternity';
};
.play {
-webkit-appearance: none;
appearance: none;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
display: flex;
justify-content: center;
align-items: center;
width: 90px;
height: 90px;
border-radius: 50%;
cursor: pointer;
border: 9px solid blue;
background: transparent;
filter: drop-shadow(3px 3px 3px #000000b3);
}
<button class="play" type="button" aria-label="Open"></button>
uj5u.com熱心網友回復:
與您評論中的jsfiddle相關:
不要this用于訪問按鈕。相反,只需使用document.querySelector:
document.querySelector('button').onclick = function() {
var sec = secondsSinceEnter();
if (sec < 10)
document.querySelector('button').innerText = sec " seconds";
else
document.querySelector('button').innerText = 'You are here like for eternity';
}
然后,您只需添加單擊按鈕的時間。此外,您應該每 0 毫秒(每個“滴答聲”)使用setInterval. 這樣您就不必撰寫兩次函式,您可以將其定義為單獨的函式。最后,洗掉單擊按鈕時的間隔。
完整腳本:
// Interval
var interval;
// Counter
var enterDate = new Date();
function secondsSinceEnter()
{
return (new Date() - enterDate) / 1000;
}
// Event function
function evtFct()
{
var sec = secondsSinceEnter().toFixed(3);
if (sec < 10)
document.querySelector('button').innerText = sec " seconds";
else
document.querySelector('button').innerText = 'You are here like for eternity';
}
// Add interval to keep the current time uptodate
interval = setInterval(evtFct, 0); // Call evtFct every tick
// Usage example
document.querySelector('button').onclick = function()
{
evtFct();
clearInterval(interval); // Disable interval
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/421958.html
標籤:
