javascript - 悬停多个实例 div 时发出独特的声音

标签 javascript jquery html audio hover

当我将鼠标悬停在具有特定类(.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;
    }
);

现场演示: http://jsfiddle.net/oscarj24/VwSLj/5/

关于javascript - 悬停多个实例 div 时发出独特的声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21047638/

相关文章:

javascript - $.inArray 不适用于对象 JavaScript 对象有其他选择吗?

Javascript - 将属性拉入数组/根据属性删除项目

javascript - 传单鼠标悬停弹出数组列表

javascript - 为什么简单的 html 和 css 在 Angular 2 元素中的工作方式与 vanilla html 网站不同

html - 3 列 div 没有完全居中

javascript - 如何在谷歌浏览器中调用运行/调用本地应用程序

javascript - 基于滚动显示图像的新部分

javascript - Sequelize "WHERE"子查询中的子句

javascript - Application Insights 保存 javascript 跟踪

javascript - JSON : The request sent by the client was syntactically incorrect