我有一个循环内的音轨(每当有人发布新曲目时),因此会在页面上放置多个音轨。这是输出到页面上的内容的html:
<html>
<div class='wrap'>
<audio id='music' preload='true'>
<source src='$file' type='audio/mpeg'>
</audio>
<div class='player paused'>
<div class='progress-bar'>
<div class='runner'></div>
</div>
<div class='description'>
<div class='title'>Something from nothing</div>
<div class='sub-title'>by $username</div>
</div>
<div class='visualizer'>
<div></div><div></div><div></div><div>
</div><div></div><div></div><div></div> <div></div><div></div>
<div></div><div></div><div></div><div>
</div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div>
</div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div>
</div><div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div>
</div><div></div><div></div><div></div><div></div><div></div><div></div>
</div>
<div class='play-button'>
div class='lp-background'></div>
<i class='fas fa-play' id='playpress></i>
</div>
<div class='time-indicator'>
<i class='fas fa-clock'></i>
<span class='time'>03:39</span>
</div>
</div>
</div>
</div>
</html>
所有这些div都用于动画条,继承我的JavaScript:
var $visualizers = $('.visualizer>div');
var $progressBar = $('.progress-bar');
var $progressBarRunner = $progressBar.find('.runner');
var songLength = 219; //in seconds
var percentage = 0
var $time = $('.time');
var $player = $('.player');
var playRunner = null;
function go() {
playRunner = setInterval(function() {
//visualizers
$visualizers.each(function() {
$(this).css('height', Math.random() * 90 + 10 + '%');
});
//progress bar
percentage += 0.15;
if (percentage > 100) percentage = 0;
$progressBarRunner.css('width', percentage + '%');
$time.text(calculateTime(songLength, percentage));
}, 250);
};
$('.play-button').on('click', function() {
$player.toggleClass('paused').toggleClass('playing');
if (playRunner) {
clearInterval(playRunner);
playRunner = null;
$time.text(calculateTime(songLength, 100));
} else {
percentage = 0;
go();
}
});
$('.progress-bar').on('click', function(e) {
var posY = $(this).offset().left;
var clickY = e.pageX - posY;
var width = $(this).width();
percentage = clickY / width * 100;
});
function calculateTime(songLength, percentage) {
//time
var currentLength = songLength / 100 * percentage;
var minutes = Math.floor(currentLength / 60);
var seconds = Math.floor(currentLength - (minutes * 60));
if (seconds <= 9) {
return (minutes + ':0' + seconds);
} else {
return (minutes + ':' + seconds);
}
}
clearInterval(playRunner);
我的问题是,当我按其中一个曲目上的播放按钮时,它们都会同时开始播放。我希望它能够在单击一个轨道的时候进行播放。我不确定它是否可以在html或javascript文件中更改,或者我只是采用不同的方式。
答案 0 :(得分:1)
在HTML中,id属性应该是唯一的。尝试删除id =&#39;音乐&#39;。