我正在尝试使用jquery为我的所有导航按钮创建随机音频效果基本上这个想法是你将鼠标悬停在独特的导航div上并播放来自阵列的随机音频mp3文件
<!DOCTYPE html>
<html>
<head>
<title>AAARGH CARIBBEAN PIRATES</title>
<meta charset = "utf8">
<link rel = "stylesheet" href = "main.css">
<script src = "jq/jquery-1.10.2.js"></script>
</head>
<body>
<div class = "wrapper">
<div class = "navmain">
<div class = "navbox">
<p class = "navi"><a href = "arms.html">arms</a></p>
</div>
<div class = "navbox">
<p class = "navi"><a href = "map.html">map</a></p>
</div>
<div class = "navbox">
<p class = "navi"><a href = "ship.html">ship</a></p>
</div>
<div class = "navbox">
<p class = "navi"><a href = "facts.html">facts</a></p>
</div>
<div class = "navbox">
<p class = "navi"><a href = "speech.html">speech</a></p>
</div>
</div>
<div id = "home">
<div id = "innerhome">
<p class = "basic">
AAARGH mateys, the caribbean was a ..
</p>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('.navbox').onmouseover(playSound());
});
function playSound(){
var audio[];
audio[0] = new Audio("assetts/audio/bird.mp3");
audio[1] = new Audio("assetts/audio/cannon.mp3");
audio[2] = new Audio("assetts/audio/fire.mp3");
audio[3] = new Audio("assetts/audio/monkey.mp3");
audio[4] = new Audio("assetts/audio/crows.mp3");
audio[5] = new Audio("assetts/audio/cannon2.mp3");
var x = Math.floor((Math.random()*1000) % 6);
audio[x].play();
}
</script>
</body>
它没有工作..不确定我哪里出错了
答案 0 :(得分:0)
给定代码存在多个问题。
<强> HTML 强>
首先是一个建议。您应该将导航标记重建为更常见,更现代和可访问的内容,例如:
<nav>
<ul class="navmain">
<li class="navbox"><a href="arms.html">arms</a></li>
<li class="navbox"><a href="map.html">map</a></li>
<li class="navbox"><a href="map.html">map</a></li>
<li class="navbox"><a href="ship.html">ship</a></li>
<li class="navbox"><a href="facts.html">facts</a></li>
<li class="navbox"><a href="speech.html">speech</a></li>
</ul>
</nav>
<强>的JavaScript 强>
这是最终的和有效的JavaScript部分:
var current = null;
var audio = [
new Audio("assetts/audio/bird.mp3"),
new Audio("assetts/audio/cannon.mp3"),
new Audio("assetts/audio/fire.mp3"),
new Audio("assetts/audio/monkey.mp3"),
new Audio("assetts/audio/crows.mp3"),
new Audio("assetts/audio/cannon2.mp3")
];
function playSound() {
if (null !== current) {
audio[current].pause();
}
current = Math.floor((Math.random() * 1000) % 6);
audio[current].play();
}
$(document).ready(function() {
$('.navbox').mouseover(playSound);
});
<强>演示强>
进一步解释
var audio[];
将不起作用,例如在C ++中,string audio[6];
有效。但是,你可以像我在初始化时那样插入所有元素,或者你可以像这样创建一个空数组:
var audio = [];
jQuery函数不是.onmouseover
而是.mouseover()
。你可以传入一个没有大括号的函数名,比如:
$('.navbox').mouseover(playSound);
或者您可以创建一个函数,例如:
$('.navbox').mouseover(function() { playSound(); } );
最后我创建了audio
- 数组全局,你没有重新创建它和每次用户悬停其中一个项目时的所有六个音频元素,我将当前播放的一个存储在一个变量中,所以在开始新声音之前你可以阻止它。
希望这有帮助。