我在我的网站上添加了一个音频(自动播放)。还有一个音乐图标(fontawesome)。其实我想暂停和播放音乐,图标也应该同时切换。 这是我的HTML标记:
<li class="music-icon">
<a href="#" onclick="pauseAudio()" >
<i class="fa fa-music"></i>
</a>
</li>
<audio autoplay loop id="myAudio">
<source src="music/guitar.mp3">
</audio>
这是我的JS脚本:
(function(){
//audio Play and Pause
var audio = document.getElementById('myAudio');
$( ".music-icon a" ).click(function( event ) {
//prevent a default
event.preventDefault();
//toggle font awesome icon (on/pause)
$(this).find('i').toggleClass('fa-volume-off');
});
//play/pause
function playAudio(){
audio.play();
}
function pauseAudio(){
audio.pause();
}
})();
答案 0 :(得分:3)
这是我的代码,告诉我是否可以改进我的解决方案。如果您想要更准确的模拟,请包括您的CSS。
window.addEventListener('load', function() {
var playing = true;
var audio = document.getElementById('myAudio');
document.getElementById('audioMusicToggle').onclick = function() {
if (playing == true) {
//pause the music
audio.pause();
playing = false;
} else {
audio.play();
playing = true;
}
};
});
&#13;
<!--http://www.freelancezonebd.com/jim/st/music/guitar.mp3-->
<li class="music-icon">
<input type="button" id="audioMusicToggle" value="Play/Pause">
</li>
<audio autoplay loop id="myAudio" controls>
<source src="http://www.freelancezonebd.com/jim/st/music/guitar.mp3">
</audio>
&#13;
答案 1 :(得分:1)
<强>的JavaScript 强>
var aIcon = document.querySelector('.music-icon a');
aIcon.addEventListener('click', function (event) {
event.preventDefault();
event.target = this;
var aPlayer = document.getElementById('aPlayer');
if (!aPlayer.paused) {
aPlayer.pause();
this.querySelector('i').classList.add('fa-music');
this.querySelector('i').classList.remove('fa-volume-off');
} else {
aPlayer.play();
this.querySelector('i').classList.add('fa-volume-off');
this.querySelector('i').classList.remove('fa-music');
}
}, false);
<强> HTML 强>
<li class="music-icon"><a href="#"><i class="fa fa-music"></i></a>
</li>
<!--change fa-music to fa-volume-off if autoplay-->
<audio loop id="aPlayer">
<source src="https://glpjt.s3.amazonaws.com/so/av/111.mp3">
</audio>
<强> CSS 强>
li {
list-style: none;
}
答案 2 :(得分:0)
您可能想尝试直接获取元素
试
$("#audioContainer")[0].pause();
答案 3 :(得分:0)
我最终使用了一些CSS技巧完成了它。现在音频有控件attr。使用css我只是让控件在图标上透明。单击透明音频控件时图标会切换。 标记:
<li class="music-icon">
<a href="#"><i class="fa fa-music"></i></a>
<audio autoplay loop id="myAudio" controls>
<source src="music/guitar.mp3">
</audio>
CSS:
/*Music*/
.music-icon {
cursor: pointer;
margin-right: 20px;
overflow: hidden;
position: relative;
width: 30px;
}
audio#myAudio {
left: 0;
opacity: 0;
padding-right: 10px;
position: absolute;
top: 12px;
}
和jQuery:
$('.music-icon').click(function(){
$(this).find('a i').toggleClass('fa-volume-off');
});
可能不是全球解决方案,但它对我有用。现在看到结果: http://www.freelancezonebd.com/jim/st/