(我是 JS 和 jQuery 的新手,所以请原谅任何不检点的行为!)
当我将鼠标悬停在其他元素上时,我尝试随机更改音频元素中的 src。我已经将一些东西拼凑在一起,并通过带有内联 JS 的按钮让它工作(感谢我目前找不到的答案),但无法让它在 .hover 上工作。
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/