更改点击脚本中的文字

时间:2019-03-16 02:33:53

标签: javascript jquery html css

我正在编码一个音频播放器,该音频播放器可以在按钮上播放/暂停,但也可以自动播放。因此出现的第一个按钮是“暂停”按钮,单击它会暂停音频并更改为“播放”按钮。现在,我尝试在其下添加“正在播放”或“已暂停”的文本。我设法做到了,但这仅在单击按钮时发生。因此,当我刷新网站时,在播放音频时没有任何文本,那么我必须单击它,它会先显示为“暂停”,然后再单击“播放”。

所以我希望“播放”位于“暂停”按钮下,而无需单击它。

function changeImage() {
  var image = document.getElementById('player');
  if (image.src.match("pause")) {
    image.src = "assets/img/icons/play.png";
    document.getElementById("fetch").innerHTML = "Paused";
  } else {
    image.src = "assets/img/icons/pause.png";
    document.getElementById("fetch").innerHTML = "Playing";
  }
}
var playing = true;

function action() {
  var audio = document.getElementById("audio");
  if (playing === false) {
    audio.play();
    playing = true;
    document.getElementById("append").innerHTML = "Playing";
  } else {
    audio.pause();
    playing = false;
  }
}
#audioplayer {
  position: relative;
  left: 65px;
  bottom: 11px;
  float: right;
  z-index: 100;
  cursor: pointer;
  height: 81px;
  width: 81px;
  border-radius: 50%;
  background-color: #0FB6D1;
}

#audioplayer:hover {
  -moz-box-shadow: 0 0 20px #6854e7;
  -webkit-box-shadow: 0 0 20px #6854e7;
  box-shadow: 0px 0px 20px #6854e7;
}

#fetch {
  font-family: 'gothic';
  text-align: center;
  font-weight: 500;
  margin-left: 1.9px;
}
<div id="audioplayer">

  <img id="player" onclick="action();changeImage();" src="assets/img/icons/pause.png" />

  <audio id="audio" src="assets/music/music.wav" loop autoloop autoplay></audio>

  <p id="fetch"></p>
  <p id="append"></p>

</div>

1 个答案:

答案 0 :(得分:0)

我不确定为什么要使用“提取”和“附加” div,因此在此示例中我删除了一个。

document.getElementById('player').addEventListener('click', function() {
  action();
});

var playing = true;
var image = document.getElementById('player');
function action() {
  var audio = document.getElementById("audio");
  if (playing === false) {
    audio.play();
    playing = true;
    document.getElementById("fetch").innerHTML = "Playing";
    image.src = "assets/img/icons/pause.png";
  } else {
    audio.pause();
    playing = false;
    document.getElementById("fetch").innerHTML = "Paused";
    image.src = "assets/img/icons/play.png";
  }
}

HTML:

<div id="audioplayer">

  <img id="player" src="assets/img/icons/pause.png" />

  <audio id="audio" src="assets/music/music.wav" loop autoloop autoplay></audio>

  <p id="fetch">Playing</p>

</div>