2016-05-31 4 views
0

Привет, я пытаюсь выяснить, как бы я положил 10 секундную задержку для мыши, чтобы начать воспроизведение звука?Как добавить задержку для мыши на звук (звук при зависании)

Вот код, с которым я работал.

function PlaySound(soundobj) { 
 
    var thissound = document.getElementById(soundobj); 
 
    thissound.play(); 
 
} 
 

 
function StopSound(soundobj) { 
 
    var thissound = document.getElementById(soundobj); 
 
    thissound.pause(); 
 
    thissound.currentTime = 0; 
 
}
<div onmouseover="PlaySound('mySound')" onClick="StopSound('mySound')">

ответ

0

Вы можете добавить тайм-аут, который будет называться после определенного количества миллисекунд.

function PlaySound(soundobj) { 
    setTimeout(function() { 
    var thissound = document.getElementById(soundobj); 
    thissound.play(); 
    }, 10 * 1000); 
} 
1

Вы можете попробовать это, если хотите, чтобы события отслеживали таймаут, а также воспроизводит ли звук звук или нет.

function MouseAudio(element, audio) { 
 
    this.div = element; 
 
    this.audio = audio; 
 
    this.timeout = null; 
 

 
    this.init(); 
 
} 
 

 
MouseAudio.prototype.init = function() { 
 
    var self = this; 
 

 
    this.div.addEventListener('mouseover', function(event) { 
 
    console.log('moused over - timeout set'); 
 

 
    if (self.timeout) { 
 
     clearTimeout(self.timeout); 
 
    } 
 

 
    self.timeout = setTimeout(function() { 
 
     console.log('playing sound'); 
 
     self.audio.play(); 
 
     self.timeout = null; 
 
    }, 10000); 
 
    }); 
 

 
    this.div.addEventListener('mouseout', function() { 
 
    if (self.timeout) { 
 
     console.log('moused out - timeout cancelled'); 
 
     clearTimeout(self.timeout); 
 
     self.timeout = null; 
 
    } else if (!self.audio.paused) { 
 
     console.log('moused out - pausing sound'); 
 
     self.audio.pause(); 
 
     self.audio.currentTime = 0; 
 
    } 
 
    }); 
 

 
    this.div.addEventListener('click', function() { 
 
    if (self.timeout) { 
 
     console.log('clicked - timeout cancelled'); 
 
     clearTimeout(self.timeout); 
 
     self.timeout = null; 
 
    } else if (!self.audio.paused) { 
 
     console.log('clicked - pausing sound'); 
 
     self.audio.pause(); 
 
     self.audio.currentTime = 0; 
 
    } 
 
    }); 
 
}; 
 

 
var mouseAudio = new MouseAudio(document.getElementById('div'), document.getElementById('audio'));
#div { 
 
    background: grey; 
 
    width: 100px; 
 
    height: 100px; 
 
    line-height: 100px; 
 
    text-align: center; 
 
}
<div id="div">Click Me</div> 
 
<audio id="audio" src="http://anything2mp3.com/system/files/mstr1/Rick%20Astley%20-%20Never%20Gonna%20Give%20You%20Up_dQw4w9WgXcQ_youtube.mp3"></audio>

+0

Спасибо, сэр :) – troxie