当我将鼠标悬停在具有特定类(.trigger)的一个 div 元素上时,我尝试播放一种独特的声音。 我的问题是,我有这个 div 类的多个实例,这意味着无论我悬停在哪个 div 上,都会播放(相同的)声音。
我的梦想场景是,一旦下一个 div 悬停(并希望播放下一个声音),任何先前的声音都会停止(我使用的声音文件长度为 1-2 秒) )。
我已通过 html5 将音频包含在我尝试用作触发器的 div 中。
<div class="trigger">
<audio id="sound" preload="auto">
<source src="sound1.mp3"></source>
<source src="sound1.mp3"></source>
</audio>
</div>
<div class="trigger">
<audio id="sound" preload="auto">
<source src="sound2.mp3"></source>
<source src="sound2.mp3"></source>
</audio>
</div>
我正在使用这个脚本:
$(".trigger")
$(this).each(function(i) {
if (i != 0) {
$("#sound")
.clone()
.attr("id", "sound" + i)
.appendTo($(this).parent());
}
$(this).data("cnt", i);
})
$(this).mouseenter(function() {
$("#sound" + $(this).data("cnt"))[0].play();
});
$("#sound").attr("id", "sound0");
如果有任何帮助和更好的想法来实现这一目标,我将不胜感激:) 我是一个糟糕的新手 - 对此感到抱歉。
最佳答案
就这么简单吗?
$('.trigger').hover(
function() {
sound = $(this).children()[0];
sound.play();
}, function() {
sound.pause();
sound.currentTime = 0;
}
);
关于javascript - 悬停多个实例 div 时发出独特的声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21047638/