if(stopwatch >= track[song].duration)
track[song].duration 查找音云轨道的持续时间。
track[song].duration
我希望创建一个秒表功能,当您单击swapID stopwatch时,该功能将开始计时毫秒,以便当该功能被“单击”一定时间后,if函数将执行某些操作。就我而言,替换图像。并且该函数将在再次单击时将其自身重置。
swap
stopwatch
就像stopwatch= current time- clicked time我该如何设置clicked time
current time
clicked time
current time= new Date().getTime();?这是毫秒吗?
new Date().getTime();
$('#swap').click(function()...
[jsbin.com demo](http://jsbin.com/IgaXEVI/167/edit)
您会看到演示代码只是一个开始/停止/重置毫秒计数器。如果您想按时进行奇特的格式化,那完全取决于您。这应该足以让您入门。
这是一个有趣的小项目。这是我的处理方式
var Stopwatch = function(elem, options) { var timer = createTimer(), startButton = createButton("start", start), stopButton = createButton("stop", stop), resetButton = createButton("reset", reset), offset, clock, interval; // default options options = options || {}; options.delay = options.delay || 1; // append elements elem.appendChild(timer); elem.appendChild(startButton); elem.appendChild(stopButton); elem.appendChild(resetButton); // initialize reset(); // private functions function createTimer() { return document.createElement("span"); } function createButton(action, handler) { var a = document.createElement("a"); a.href = "#" + action; a.innerHTML = action; a.addEventListener("click", function(event) { handler(); event.preventDefault(); }); return a; } function start() { if (!interval) { offset = Date.now(); interval = setInterval(update, options.delay); } } function stop() { if (interval) { clearInterval(interval); interval = null; } } function reset() { clock = 0; render(); } function update() { clock += delta(); render(); } function render() { timer.innerHTML = clock/1000; } function delta() { var now = Date.now(), d = now - offset; offset = now; return d; } // public API this.start = start; this.stop = stop; this.reset = reset; };
获取一些基本的HTML包装器
<!-- create 3 stopwatches --> <div class="stopwatch"></div> <div class="stopwatch"></div> <div class="stopwatch"></div>
从那里开始使用就变得很简单
var elems = document.getElementsByClassName("stopwatch"); for (var i=0, len=elems.length; i<len; i++) { new Stopwatch(elems[i]); }
另外,您还可以获得计时器的可编程API。这是一个用法示例
var elem = document.getElementById("my-stopwatch"); var timer = new Stopwatch(elem, {delay: 10}); // start the timer timer.start(); // stop the timer timer.stop(); // reset the timer timer.reset();
至于jQuery部分,一旦您拥有了上述不错的代码组成,编写jQuery插件就很容易了
(function($) { var Stopwatch = function(elem, options) { // code from above... }; $.fn.stopwatch = function(options) { return this.each(function(idx, elem) { new Stopwatch(elem, options); }); }; })(jQuery);
jQuery插件用法
// all elements with class .stopwatch; default delay (1 ms) $(".stopwatch").stopwatch(); // a specific element with id #my-stopwatch; custom delay (10 ms) $("#my-stopwatch").stopwatch({delay: 10});