首页 > 解决方案 > 请使用相同的按钮播放和暂停音频

问题描述

我有这段代码,只是播放,但我想用同一个按钮(图像)播放和暂停,我不知道我需要添加什么,我需要做什么?请帮帮我

        <script>
          function play(){
               var audio = document.getElementById("audio");
               audio.play();
                         }
           </script>

        <input type="image" id= "Portada1" src= "https://66.media.tumblr.com/dc48784826909289a58767fed35ba421/tumblr_pu7p4w8Jai1yrcbyio1_1280.jpg" alt ="Portada del sencillo Tim McGraw de Taylor Swift." onclick="audio.play  ()">


        <audio id="audio" src="Audio/Teardrops On My Guitar.mp3" ></audio>

         </body>

标签: javascripthtml

解决方案


<input type='image'>实际上是花哨的提交按钮,当嵌套在 a 中时可以实现全部功能<form>,但出于 OP 的目的,<button>带有 a 的 abackground-image不仅在语义上是准确的,而且还确保不会有任何可能的副作用。

  <button type='button'></button>

  button { background: url(https://example.com/path/to/image.jpg)....}

要在音频对象上切换.play().pause()方法,请使用

  if (audio.paused || audio.ended) {... //if audio is not playing

或者

  if (audio.playing) {... // if audio is playing

document.querySelector('button').onclick = player;

function player(event) {
  const clicked = event.target;
  clicked.classList.toggle('playing');
  const song = document.querySelector('audio');
  if (song.paused || song.ended) {
    song.play();
  } else {
    song.pause();
  }
}
button {
  background: url(https://www.hardwoodandhollywood.com/pop-culture-spin/wp-content/uploads/sites/7/2015/02/florencemachine.jpg)no-repeat;
  background-size: contain;
  display: inline-block;
  width: 124px;
  height: 86px;
  cursor: pointer;
  border: 3px solid rgba(158, 127, 103, 0.7);
  box-shadow: 4px 6px 7px rgba(158, 127, 103, 0.6);
  border-radius: 20%;
}

button:hover {
  border: 3px solid rgba(158, 127, 103, 1);
}

.playing {
  border: 3px solid rgba(58, 127, 203, 0.7);
  box-shadow: 4px 6px 7px rgba(58, 127, 203, 0.6);
}

.playing:hover {
  border: 3px solid rgba(58, 127, 203, 1);
}

button:focus {
  outline: 0
}
<button type='button'></button>
<audio src='https://gldrv.s3.amazonaws.com/av/Florence_and_the_Machine-Dog_%20Days_are_Over.mp3'></audio>


推荐阅读