javascript - 如何将按钮更改为可点击的图像

标签 javascript html css

所以我在这里有我的音乐播放器代码,但是,我一直在尝试将带有文本的按钮更改为图像以切换音乐,而且当单击时更改图像(静音/取消静音图像)我是但难住了,所以欢迎任何评论。

function aud_play_pause() {
  var myAudio = document.getElementById("myAudio");
  if (myAudio.paused) {
    myAudio.play();
  } else {
    myAudio.pause();
  }
}
div {}

button {
  top: 0%;
  width: 10%;
  left: 0;
  position: absolute;
}
<audio id="myAudio">
 <source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.mp4"
         type='audio/mp4'>
 <source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.oga"
         type='audio/ogg; codecs=vorbis'>
 Your user agent does not support the HTML5 Audio element.
</audio>
<div>
  <button type="button" onclick="aud_play_pause()">Play or Pause Music</button>
</div>

最佳答案

您可以使用普通图像标签并注册 EventListener在那个图像上。然后,在每次点击时,相应地更改图像源。

var button = document.getElementById("button"); // Button global, we need it twice

// EventListener to call the function when the image gets clicked
button.addEventListener("click", aud_play_pause);

function aud_play_pause() {
  var myAudio = document.getElementById("myAudio");
  if (myAudio.paused) {
    myAudio.play();
    // Making your "button" interactive by changing the source to be another image
    button.src = "https://proxy.duckduckgo.com/iu/?u=https%3A%2F%2Ftse2.mm.bing.net%2Fth%3Fid%3DOIP.kNbNpabwx-O1Fh2tvxwYdwHaHa%26pid%3D15.1&f=1";
  } else {
    myAudio.pause();
    // Here too
    button.src = "https://proxy.duckduckgo.com/iu/?u=https%3A%2F%2Fimage.flaticon.com%2Ficons%2Fpng%2F512%2F26%2F26025.png&f=1";
  }
}
#button {
  top: 0%;
  width: 10%;
  left: 0;
  position: absolute;
}
<audio id="myAudio">
 <source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.mp4"
         type='audio/mp4'>
 <source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.oga"
         type='audio/ogg; codecs=vorbis'>
 Your user agent does not support the HTML5 Audio element.
</audio>
<div>
  <img id="button" src="https://proxy.duckduckgo.com/iu/?u=https%3A%2F%2Fimage.flaticon.com%2Ficons%2Fpng%2F512%2F26%2F26025.png&f=1" />
</div>

关于javascript - 如何将按钮更改为可点击的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55671008/

相关文章:

javascript - jquery onclick 过早触发(?)

c# - 这可以通过 javascript 实现吗?

javascript - 未定义的函数

android - Chrome for Android contenteditable 错误

JAVA解析特殊字符

html - 工具提示底部定位

javascript - IOS Safari : clipping of iframe when using transform3d

javascript - jquery中的append()不会第二次追加文件

html - HTML 中的可滚动表格无法正确显示

html - 使用 margin 0 auto 居中 div