当长按是hapening时发出声音

时间:2017-11-21 22:02:09

标签: javascript jquery wordpress

我正在使用此脚本来检测鼠标是否按下了一个元素(链接内部有图像)更长的时间(不仅仅是点按):

https://jsfiddle.net/gianlucaguarini/56Szw/

我正在尝试修改此脚本,使其使用可单独运行的脚本播放声音: JS:

function PlaySound() {
          var sound = document.getElementById("audio");
          sound.play()
      }

HTML

<audio id="audio" src="sound.mp3" autostart="false" ></audio>
    <a onclick="PlaySound()"> Play</a>

但事情对我不起作用,这是我的代码:

HTML:

    <div id="touchArea">
<audio id="audio" src="sound.mp3" autostart="false" ></audio>
    <a onclick="PlaySound()"> Play</a>
 </div>

JS:

var getPointerEvent = function(event) {
    return event.originalEvent.targetTouches ? event.originalEvent.targetTouches[0] : event;
};
var jQuerytouchArea = jQuery('#touchArea'),
    touchStarted = false, // detect if a touch event is sarted
    currX = 0,
    currY = 0,
    cachedX = 0,
    cachedY = 0;
//setting the events listeners
jQuerytouchArea.on('touchstart mousedown',function (e){
    e.preventDefault(); 
    var pointer = getPointerEvent(e);
    // caching the current x
    cachedX = currX = pointer.pageX;
    // caching the current y
    cachedY = currY = pointer.pageY;
    // a touch event is detected      
    touchStarted = true;
    jQuerytouchArea.text('Touchstarted');
    // detecting if after 200ms the finger is still in the same position
    setTimeout(function (){
        if ((cachedX === currX) && !touchStarted && (cachedY === currY)) {
            // Here you get the Tap event
            jQuerytouchArea.text('Tap');
        }
    },200);
});
jQuerytouchArea.on('touchend mouseup touchcancel',function (e){
    e.preventDefault();
    // here we can consider finished the touch event
    touchStarted = false;
    jQuerytouchArea.text('Touchended');
});
jQuerytouchArea.on('touchmove mousemove',function (e){
    e.preventDefault();
    var pointer = getPointerEvent(e);
    currX = pointer.pageX;
    currY = pointer.pageY;
    if(touchStarted) {
// here is what should happen when the button is pressed for a long time
function PlaySound() {
      var sound = document.getElementById("audio");
      sound.play()
  }  
    }
});

0 个答案:

没有答案