我正在为一所大学项目工作,我似乎遇到了问题。 当用户点击地图上的某个地方时,它应该播放声音片段 这是我的代码:
// Container to retrieve all hyperlinks within map overlay (points of interest)
var markers = document.querySelectorAll('.mapOverlay a');
// Constructor for new audio component for playback
var audioPlayer = new Audio();
// Iterate through all found markers
for (var i = 0; i < markers.length; i++) {
// Add CLICK event handler to each point
markers[i].addEventListener('click', function(event) {
// Cancel actual hyperlink request
event.preventDefault();
// Get audio source file from hyperlink
var audioSrc = this.getAttribute("href");
// If this point is already playing the audio, stop it and exit
if (!audioPlayer.paused && audioPlayer.src === audioSrc) {
audioPlayer.pause();
return;
}
// Set audio player source
audioPlayer.src = audioSrc;
// Play audio file
audioPlayer.play();
});
}
/* World Map Image / Container */
#WorldMap {
width: 800px;
height: 600px;
position: relative;
background: #000 url(https://i.imgur.com/HnEMwm1.png) top left no-repeat;
}
/* Overlay Hyperlink (Point of Interest Base) */
.mapOverlay a {
display: block;
z-index: 100;
position: absolute;
width: 25px;
height: 25px;
border: none;
border-radius: 15px;
box-shadow: 0 0 10px rgba(0, 0, 0, 1.0);
}
/* Specific Point of Interest - Washington D.C. */
.mapOverlay a.point1 {
left: 190px;
top: 270px;
background-color: pink;
}
/* Specific Point of Interest - Japan */
.mapOverlay a.point2 {
left: 675px;
top: 270px;
background-color: cyan;
}
.mapOverlay a.point3 {
left: 300;
top: 400;
background-color: yellow;
}
<!DOCTYPE.html>
<html>
<head>
<title>World Map</title>
<link href="style.css" type="text/css" rel="stylesheet" />
<link src="javascript.js" />
</head>
<body>
<div id="WorldMap">
<div class="mapOverlay">
<a class="point1" href="https://upload.wikimedia.org/wikipedia/en/6/61/I_Have_A_Dream_sample.ogg"></a>
<a class="point2" href="https://upload.wikimedia.org/wikipedia/en/3/3d/7_sample.ogg"></a>
<a class="point3" href="sounds/test.ogg"></a>
</div>
</div>
</body>
</html>
问题是我不想打开链接,只是播放音频剪辑。但是event.preventDefault();
不起作用,链接会打开。
由于某种原因,当我把它放在这里时,代码片段似乎有效
谁能告诉我这是什么问题?