javascript - 悬停时随机更改音频源?

标签 javascript jquery html5-audio

(我是 JS 和 jQuery 的新手,所以请原谅任何不检点的行为!)

当我将鼠标悬停在其他元素上时,我尝试随机更改音频元素中的 src。我已经将一些东西拼凑在一起,并通过带有内联 JS 的按钮让它工作(感谢我目前找不到的答案),但无法让它在 .hover 上工作。

I have this jsFiddle

JS: 函数声音(){

var rand = [
    'http://thejazz.ninja/sounds/v.mp3',
    'http://thejazz.ninja/sounds/w.mp3',
    'http://thejazz.ninja/sounds/x.mp3',
    'http://thejazz.ninja/sounds/y.mp3',
    'http://thejazz.ninja/sounds/z.mp3'];

var randSound = rand[Math.floor(Math.random() * rand.length)];

var player=document.getElementById('player');
var sourceMp3=document.getElementById('sourceMp3');

sourceMp3.src='' + randSound + '';

   player.load();
   player.play();
}

$('.box').click(sounds); // this doesn't work...

HTML:

<audio id="player" autoplay>
  <source id="sourceMp3" src="" type="audio/mp3" />
      Your browser does not support the audio element.
</audio>

<p>
    <button onclick='sounds()'> Load Sound</button> <!-- THIS works -->
</p>

CSS:

.box {
    display:inline-block;
    width:50px;
    height:50px;
    background:#aee;
}

最佳答案

$('.box').click(sounds);

执行时没有.box。用 $ 包裹它:

$(function(){                       //this function will be executed when DOM is
    $('.box').click(sounds);        //ready to be manipulated (!= onload)
});

或者在 jsFiddle 中,您可以选择左侧的“onLoad”/“onDomready”,而不是“No wrap - in ”:http://jsfiddle.net/DerekL/D8Ln7/6/

<小时/>

关于“hover”部分,将click改为mouseenter :

$(function(){
    $(".box").mouseenter(sounds);
});

不要使用.hover。有一个方法hover在 jQuery 中,但这在这种情况下不起作用,因为它与您想要执行的操作不匹配。引用文档:

[.hover] will execute that handler for both mouseenter and mouseleave events.

更新的 fiddle :http://jsfiddle.net/DerekL/D8Ln7/8/

关于javascript - 悬停时随机更改音频源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25131284/

相关文章:

javascript - 使用 pdf.js 显示具有透明背景的 pdf

javascript - 使用 Howler.js 时有没有办法指示音频下载进度/缓冲区?

javascript - 如何使用 angularJs 创建具有连续数字的多维矩阵

javascript - 将引用编号传递给数据控制者

带阴影的 JQueryUI 选项卡

javascript - 如何获取 <td> 内的跨度值(表数据),当单击也在 <td> 内的按钮时

javascript - 未捕获引用错误 BufferLoader 未定义

javascript - 在移动设备上加载页面后更改 <audio> src 后没有声音播放

javascript - 使用地址栏参数进行客户端重定向

jquery - 使用 jQuery 将 JavaScript 对象转换为 JSON 字符串