我希望在单个按钮上两次点击之间得到时差.
我有这样的标记
<a href="#">click here</a>
我使用此代码来获取两次点击之间的时差.
var clickedTime = '';
var lastClicked = '';
$('body').on('click', 'a', function(e) {
var d = new Date();
clickedTime = lastClicked;
lastClicked = d.getTime();
console.log(clickedTime);
console.log(lastClicked);
});
但它在两个控制台同时显示.那么有人能告诉我如何获得时差吗?
最佳答案 这是一个简单的jQuery函数,可以为每x次点击返回所需格式的时差 –
Demo
<button>Get Time Difference</button>
(function ($) {
$.fn.clickTimer = function ($param, $numbClicks) {
function msTotime(ms) {
var mill = ms % 1000;
var seconds = Math.floor((ms / 1000) % 60);
var minutes = Math.floor((ms / (60 * 1000)) % 60);
switch ($param) {
case "ms":
return ms;
break;
case "s":
return seconds;
break;
default:
return [minutes, seconds, mill];
}
}
var counter = 0;
var Start_Time;
this.click(function (event) {
counter++;
if (counter == $numbClicks) {
counter = 0;
var now = event.timeStamp;
Diff = now - Start_Time;
console.log(msTotime(Diff));
} else {
Start_Time = event.timeStamp;
}
});
return this;
};
})(jQuery);
用法:
$(selector).clickTimer(time format , number of clicks);
$("button").clickTimer("ms", 2);
// returns time difference in milliseconds for every 2 clicks
$("button").clickTimer("s", 2);
// returns time difference in seconds
$("button").clickTimer(false, 2);
// returns an array [minutes, seconds, milliseconds]
让我知道你的想法.这绝对不是一个完美的解决方案,但它可能会让你开始.