如何使用 Tampermonkey 为计时器/秒表添加开始和停止按钮

How to add Start and Stop buttons for a timer / stopwatch using Tampermonkey

如何创建带有计时器开始停止按钮的 Tampermonkey 代码?

是否可以创建这个?

这与 Add a JavaScript button using Greasemonkey or Tampermonkey? 类似,请参阅该问题了解格式和定位思路。

建议使用Performance API or the Moment.js library to handle the timing and/or time formatting. Or see: How to convert time milliseconds to hours, min, sec format in JavaScript?硬格式化

这里是一个完整的 Tampermonkey 用户脚本来说明基础知识。

您可以 运行 代码片段或使用 Tampermonkey 安装它以查看它的实际效果。

// ==UserScript==
// @name     _Add a stopwatch / elapsed time button
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @require  https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==

var gblButtonClickTime;

$("body").prepend ( `
    <div id="tmStopWatchBlck">
        <button id="tmStopWatchBttn">Start</button>
        <span id="tmTimeStat">&nbsp;</span>
    </div>
` );

$("#tmStopWatchBttn").click ( zEvent => {
    var statusNode  = $("#tmTimeStat");
    var tmrButton   = $(zEvent.target);

    //--- Button text is either "Start" or "Stop".
    if (tmrButton.text() === "Start") {
        //-- Start the timer
        tmrButton.text ("Stop");
        statusNode.css ("background", "lightyellow");

        gblButtonClickTime = performance.now ();
        console.log (
            "Timer started at: ", gblButtonClickTime.toFixed(0), new Date()
        );
    }
    else {
        //-- Stop the timer
        tmrButton.text ("Start");
        statusNode.css ("background", "lightgreen");

        var stopTime        = performance.now ();
        var elapsedtime     = stopTime - gblButtonClickTime;  // Milliseconds
        var purtyElpsdTime  = (elapsedtime / 1000).toFixed(3) + " seconds";
        console.log (
            "Timer stopped at: ", stopTime.toFixed(0), new Date(),
            "Elapsed: ", purtyElpsdTime
        );
        statusNode.text (purtyElpsdTime);
    }
} );

GM_addStyle ( `
    #tmStopWatchBttn {
        font-size: 1.2em;
        padding: 0.5ex 1em;
        width: 5em;
    }
    #tmTimeStat {
        margin-left: 1em;
        padding: 0.2ex 2ex;
        border: 1px solid lightgray;
        border-radius: 0.5ex;
    }
` );

/********************************************************************
******* Everything below this block is simulated target page. *******
******* It's NOT part of the userscript.                      *******
********************************************************************/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://greasyfork.org/scripts/44560-gm-addstyle-shim/code/GM_addStyle_shim.js"></script>