我有播放/暂停图标。如果按一下,我需要打开音频。我创建了图标,但是当它按下时什么也没有发生,这意味着出了点问题。
CSS:
.player {
width: 20px;
height: 20px;
background: url('https://image.flaticon.com/icons/svg/149/149657.svg') no-repeat center center;
}
HTML:
<div class="player">
<img src="" onclick="togglePlay(this)" id="button">
<audio>
<source src="https://ccrma.stanford.edu/~jos/mp3/bachfugue.mp3" />
</audio>
</div>
JS:
function togglePlay(video) {
var audio = document.getElementsByTagName("audio")[0];
if (audio) {
if (audio.paused) {
audio.play();
document.getElementById("button").src = "https://image.flaticon.com/icons/svg/149/149658.svg";
} else {
audio.pause();
document.getElementById("button").src = "https://image.flaticon.com/icons/svg/149/149657.svg";
}
}
}
出什么问题了?我需要在CSS上放置img。如何使用图标打开音频?如果可以的话,请帮助我。谢谢。
答案 0 :(得分:0)
在播放器类上尝试onclick方法。可以。
<div class="player" onclick="togglePlay(this)">
<img src="" id="button">
<audio>
<source src="https://ccrma.stanford.edu/~jos/mp3/bachfugue.mp3" />
</audio>
</div>
答案 1 :(得分:0)
您的代码需要进行细微更改。请参见下面的代码段。
function togglePlay() {
var audio = document.getElementsByTagName("audio")[0];
if (audio) {
if (audio.paused) {
audio.play();
document.getElementById("button").src = "https://image.flaticon.com/icons/svg/149/149658.svg";
} else {
audio.pause();
document.getElementById("button").src ="https://image.flaticon.com/icons/svg/149/149657.svg";
}
}
}
.player {
width: 20px;
height: 20px;
}
<div class="player">
<img id ="button" onclick="togglePlay()" src ="https://image.flaticon.com/icons/svg/149/149657.svg">
<audio>
<source src="https://ccrma.stanford.edu/~jos/mp3/bachfugue.mp3" />
</audio>
</div>
答案 2 :(得分:0)
首先为暂停和播放定义两种样式,
.playbg{
background:url(https://image.flaticon.com/icons/svg/149/149657.svg);
}
.pausebg{
background:url(https://image.flaticon.com/icons/svg/149/149658.svg);
}
然后为玩家提供一个ID,即“玩家”以供参考...
<div id="player" class="player">
<img src="" onclick="togglePlay(this)" id="button">
<audio>
<source src="https://ccrma.stanford.edu/~jos/mp3/bachfugue.mp3" />
</audio>
</div>
在这里,我们定义脚本,并确保按以下方式加载jquery。
页面加载时,$(document).ready
会使用播放按钮初始化按钮,而
<script type="text/javascript">
//when the page loads, set the paused property to true
var paused = true;
//add the play image to the button...
$(document).ready(function(){
$('#player').find('img').addClass('playbg');
});
//and the toggle play button checks and sees if the variable is set or not, and replaces the image background, by alternating the classes using jquery.
function togglePlay() {
var audio = $('#player').find('audio');
if (paused) {
//audio.play();
$('#player').find('img').removeClass('playbg').addClass('pausebg');
paused = false;
} else {
//audio.pause();
$('#player').find('img').removeClass('playbg').addClass('pausebg');
}
}
}
</script>
<script type="text/javascript> src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>