使用js更改图标

时间:2019-03-07 15:03:31

标签: javascript html css

我有一个图标play/pause,当我单击play时,我可以看到pause,但是我有很多音频块,在我的js代码中,我可以更改第一个图标(从playpause)。如何在页面上的所有音频元素中使用它?

let playIcon = "https://image.flaticon.com/icons/svg/149/149668.svg";
let pauseIcon = "https://image.flaticon.com/icons/svg/149/149670.svg";

function togglePlay(video) {
  var audio = document.getElementsByTagName("audio")[0];
  if (!audio)
    return;
  audio.paused ? audio.play() : audio.pause();
  document.getElementById("button").src = audio.paused ? playIcon : pauseIcon;
}
#button {
  width: 50px;
  display: block;
}
<div class="player" onclick="togglePlay(this)">
  <img src="https://image.flaticon.com/icons/svg/149/149668.svg" id="button">
  <audio>
    <source src="https://ccrma.stanford.edu/~jos/mp3/bachfugue.mp3" />
  </audio>
</div>

2 个答案:

答案 0 :(得分:0)

这是一个不错的设置,应该可以解决问题:

let playIcon = "https://image.flaticon.com/icons/svg/149/149668.svg";
let pauseIcon = "https://image.flaticon.com/icons/svg/149/149670.svg";

function togglePlay(video) {
  var audio = video.querySelectorAll("audio")[0];
  if (!audio)
    return;
  audio.paused ? audio.play() : audio.pause();
  video.querySelectorAll(".button")[0].src = audio.paused ? playIcon : pauseIcon;
}
.button {
  width: 50px;
  display: block;
}
<div class="player" onclick="togglePlay(this)">
  <img src="https://image.flaticon.com/icons/svg/149/149668.svg" class="button">
  <audio>
    <source src="https://ccrma.stanford.edu/~jos/mp3/bachfugue.mp3" />
  </audio>
</div>
<div class="player" onclick="togglePlay(this)">
  <img src="https://image.flaticon.com/icons/svg/149/149668.svg" class="button">
  <audio>
    <source src="https://ccrma.stanford.edu/~jos/mp3/bachfugue.mp3" />
  </audio>
</div>
<div class="player" onclick="togglePlay(this)">
  <img src="https://image.flaticon.com/icons/svg/149/149668.svg" class="button">
  <audio>
    <source src="https://ccrma.stanford.edu/~jos/mp3/bachfugue.mp3" />
  </audio>
</div>

答案 1 :(得分:0)

不使用ID来获取按钮,而是相对于调用该函数的元素进行访问。试试这个功能。

function togglePlay(elm) {
  var audio = elm.querySelector('audio');
  if(!audio) return;

  audio.paused ? audio.play() : audio.pause();
  elm.querySelector('img').src = audio.paused ? playIcon : pauseIcon;
}