2016-05-31 95 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