我对HTML和Javascipt非常陌生。我正在一个项目上,该项目将允许用户从下拉菜单中选择四弦琴和弦,然后将鼠标悬停在图像上以播放和弦的声音。我已经将所有声音片段放置在一个数组中,并且已经有代码可以根据用户的选择更改图像的位置。尽管我正在尝试对图像和音频使用相同的方法,但我似乎还是无法播放音频。这是我到目前为止的脚本:
<script>
$(document).ready(function(){
var pictureList = [
"images/ukeneccsmall.png",
"images/c_chord.png",
"images/d_chord.png",
"images/f_chord.png",
"images/g_chord.png",
"images/aminor_chord.png"
];
var soundList = [
"sounds/No_chord.m4a",
"sounds/C_chord.m4a",
"sounds/D_chord.m4a",
"sounds/F_chord.m4a",
"sounds/G_chord.m4a",
"sounds/Am_chord.m4a"
];
$('.button').on('click',function() {
});
$("#pickme").change(function() {
//console.log("Drop down changed!");
var picked = $("#pickme option:selected").val();
var imgsrc = pictureList[picked];
var songsrc = soundList[picked];
$('#neckimg').attr("src",imgsrc);
playSound(songsrc);
});
$('#picDD').change(function () {
var val = parseInt($('#picDD').val());
//selects all images
//make individual ID
$('img').attr("src",pictureList[val]);
});
var div = $(".dropdown-content");
var div = document.getElementsByClassName('dropdown-content');
for(var i =0;i<div.length;i++) {
for(var j =0;j<div[i].children.length;j++) {
div[i].children[j].addEventListener('click',function(){
this.parentNode.previousElementSibling.innerHTML = this.innerHTML;
});
}
}
function playSound(songsrc) {
var soundPlay = songsrc;
soundplay.currentTime = 0
soundPlay.play();
}
});
</script>
这是我当前将鼠标悬停在图像上的HTML:
<img src="images/ukeneccsmall.png" height="567px" width="250px" left="10px" margin="10px" id="neckimg" float="left" align="middle" onmouseover="playSound()" >
谢谢!
您的playSound
函数存在一些问题:
function playSound(songsrc) {
var soundPlay = songsrc; //this var is camelCase
soundplay.currentTime = 0 //soundplay should be undefined and if you're not on es6 (I guess), you'll need a semikolon as well
soundPlay.play();
}
将该功能更改为:
function playSound(songsrc) {
var soundPlay = songsrc;
soundPlay.currentTime = 0;
soundPlay.play();
}
或更简单点,因为您实际上不必在这么小的辅助函数中声明新变量:
function playSound(songsrc) {
songsrc.currentTime = 0; //I personally always prefer semikolons, doesn't matter what kind a es-version it is
songsrc.play();
}
您的服装onmouseover="playSound()
没有参数,但是您的函数playSound(songsrc)
需要一个参数。看看这个问题playing-sound-file-onmouseover-event