Touchstart,touchend javascript计数器

时间:2016-07-13 19:56:41

标签: javascript android ios touchscreen

有没有办法跟踪用户手指的持续时间,每1秒更改一次html内容。

我在一篇文章中找到了这个示例http://jsfiddle.net/7Z6hg/,但它与keydown有关。

$(function () {
    var keyTimes = {};

    $(document).keydown(function (e) {
        if (keyTimes["key" + e.which]) {
            return false;
        }
        keyTimes["key" + e.which] = new Date().getTime();
    });

    $(document).keyup(function (e) {
        if (keyTimes["key" + e.which]) {
            var x = new Date().getTime() - keyTimes["key" + e.which];
            delete keyTimes["key" + e.which];
            $("<p />").text("Held key " + e.which + " for " + x / 1000.0 + " seconds").appendTo("div");
        }
    });
});

触控设备是否有任何活动?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

  • 使用Date-object获取启动了哪个活动的Date
  • 使用+(Unary plus)获取Date-object
  • 的时间戳
  • 将差额除以1000将返回seconds

&#13;
&#13;
var elem = document.getElementById('elem');
var date;
elem.addEventListener('touchstart', function() {
  date = +new Date();
});
elem.addEventListener('touchend', function() {
  var diff = +new Date() - date;
  console.log((diff / 1000).toFixed(2) + ' seconds');
});
&#13;
#elem {
  width: 100%;
  height: 200px;
  background-color: green;
}
&#13;
<div id="elem">Element</div>
&#13;
&#13;
&#13;