![](/img/trans.png)
[英]How to stop the repeat of the jQuery functions mouseenter() and mouseleave()?
[英]How to stop audio on jQuery mouseleave()
我正在使用javascriptkit.com提供的一些代码,这些代码可动态创建音频元素并加载给定的源文件。 我对其进行了一些修改,以设置循环属性,然后在jQuery mouseenter()上连续播放。 这一切都正常工作。
我添加了一个功能stopSound和jQuery mouseleave()来触发该stop方法,但是音频会继续播放,而无需将鼠标放在该元素上。 控制台没有显示任何错误,但是失败了。
这是代码
jQuery(function($) {
// Mouseover/ Click sound effect- by JavaScript Kit (www.javascriptkit.com)
// Visit JavaScript Kit at http://www.javascriptkit.com/ for full source code
// http://www.javascriptkit.com/script/script2/soundlink.shtml
var mimetype = {
"mp3": "audio/mpeg",
"mp4": "audio/mp4",
"ogg": "audio/ogg",
"wav": "audio/wav"
}
function soundFx(sound='')
{
var audioElement = document.createElement('audio');
if (audioElement.canPlayType)
{
for (var i=0; i<arguments.length; i++)
{
var src = document.createElement('source');
src.setAttribute('src', arguments[i]);
if (arguments[i].match(/\.(\w+)$/i))
src.setAttribute('type', mimetype[RegExp.$1]);
audioElement.appendChild(src);
}
audioElement.playsoundFx = function(){
audioElement.setAttribute('loop','loop');
audioElement.play();
}
// this added method does not execute
audioElement.stopSound = function() {
audioElement.pause();
audioElement.currentTime = 0;
}
return audioElement;
}
else{
return {playsoundFx:function(){
throw new Error("Your browser does not support HTML5 audio");
}
}
}
}
// sound fx trigger
$.fn.runsoundFx = function(soundfile='') {
this.mouseenter(function() {
soundFx(soundfile).playsoundFx();
});
this.mouseleave(function() {
soundFx().stopSound();
});
};
});
我需要在代码中做什么才能使音频停止在mouseleave上?
更新9/26
该代码现在可以与@PatrickEvans提供的已检查解决方案一起使用,请务必阅读他的回答,因为我将原始问题保留了下来。
如果有人想在文档中使用它,则按ID,类或元素名称将声音附加到元素的方法有:
$("#myelement").runsoundFx("/url/to/file.mp3");
或附加到所有图像
$("img").runsoundFx("/url/to/file.mp3");
或将相同的音频附加到多个类和/或ID和元素名称
$(".myclass, .otherclass, #myId, strong").runsoundFx("/url/to/file.mp3");
soundFx()
将在调用它时创建并返回一个新的音频实例。 它不会返回上一个调用中创建的实例。 您将需要修改代码以跟踪您的声音实例,测试以查看是否已经创建了声音实例,如果是,则返回它,否则,请创建它并将其添加到跟踪器中。
例如,您可以使用源URL作为键来创建Map列表。
var audioMap = new Map();
function soundFx(sound='') {
if(audioMap.has(sound)){
return audioMap.get(sound);
}
//rest of your creation code
//add instance to map before returning it
audioMap.set(sound,audioElement);
return audioElement;
}
并且在您的mouseleave中传递您的源值
$.fn.runsoundFx = function(soundfile='') {
this.mouseenter(function() {
soundFx(soundfile).playsoundFx();
});
this.mouseleave(function() {
soundFx(soundfile).stopSound();
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.