我需要实现一个简单的“秒”计数器。
想要做这样的事情:
var start = new Date();
var sectionEnd = new Date();
var startTime = start.getTime();
var sectionEndTime = sectionEnd.getTime();
$('#next').on('click', function()){
// set start time if NOT set or use set startTime
$('#start-time').text().length < 1 ? startTime : $(this).text();
// set or update section end time
$('#section-end-time').html(sectionEndTime)
// calculate the difference from startTime to current sectionEndTime
var elapsedTime = startTime - sectionEndTime;
// alert elapsed time in seconds..
alert(elapsedTime);
}
所以很明显上面是伪代码,我只是写作来说明我想要完成的事情。有一个简单的jQuery解决方案吗?也许3-4行代码没有使用外部插件?
答案 0 :(得分:0)
使用$.now()
,就像那样:
HTML:
<button id="startDate">Date</button>
<p></p>
Jquery的:
$("#startDate").on("click",function()
{
DateDifference();
});
function DateDifference()
{
var date1 = new Date($.now());
setInterval(function()
{
var date2 = new Date($.now());
var seconds = (date2 - date1)/1000;
$("p").html(seconds+" seconds of differrence between date1 and date2");
}, 1000);
}
的jsfiddle: http://jsfiddle.net/56ojwos5/