按钮onclick中更改glyphicon

时间:2015-09-11 17:03:02

标签: javascript jquery html twitter-bootstrap onclick

我想要的是一个基本的播放按钮,onclick播放一个音频文件并将其外观从glyphicon-play改为glyphicon-pause。进一步单击将暂停音频并返回播放 - glyphicon。

我所拥有的是一个允许我播放和暂停音频文件的脚本 我用按钮触发 缺少的是我的按钮中的切换glyphicon。



function EvalSound(soundobj) {
    var thissound = document.getElementById(soundobj);
    if (thissound.paused) {
      thissound.play();
    } else {
      thissound.pause();
    }
  }

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>


<audio id="SDJTrack1" preload="none" source src='http://www.salon-du-jazz.de/mp3/La_Version_del_Trabajo_Hoerprobe.mp3' type='audio/mpeg'>
</audio>

<audio id="SDJTrack2" preload="none" source src='http://www.salon-du-jazz.de/mp3/No_Matter_Hoerprobe.mp3' type='audio/mpeg'>
</audio>

<button type="button" class="btn btn-default btn-lg" onClick="EvalSound('SDJTrack1')"><span class="glyphicon glyphicon-play"></span>
</button>1. Song

<button type="button" class="btn btn-default btn-lg" onClick="EvalSound('SDJTrack2')"><span class="glyphicon glyphicon-play"></span>
</button>2. Song
&#13;
&#13;
&#13;

我找到了几种解决方案,例如: https://stackoverflow.com/a/24901840/5325923 然而,我想在我的网站上添加大约20个音频文件,这些解决方案似乎只能在第一个按钮或同时在所有按钮上工作。 处理这个问题的最佳方法是什么? 非常感谢你!

1 个答案:

答案 0 :(得分:2)

更改您的htmljs,如下所示

&#13;
&#13;
function EvalSound(soundobj, button) {
    var thissound = document.getElementById(soundobj);
    if (thissound.paused) {
      thissound.play();
      $(button).find(".glyphicon").removeClass("glyphicon-pause").addClass("glyphicon-play");
    } else {
      thissound.pause();
      $(button).find(".glyphicon").removeClass("glyphicon-play").addClass("glyphicon-pause");
    }
  }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>


<audio id="SDJTrack1" preload="none" source src='http://www.salon-du-jazz.de/mp3/La_Version_del_Trabajo_Hoerprobe.mp3' type='audio/mpeg'>
</audio>

<audio id="SDJTrack2" preload="none" source src='http://www.salon-du-jazz.de/mp3/No_Matter_Hoerprobe.mp3' type='audio/mpeg'>
</audio>

<button type="button" class="btn btn-default btn-lg" onClick="EvalSound('SDJTrack1', this)"><span class="glyphicon glyphicon-play"></span>
</button>1. Song

<button type="button" class="btn btn-default btn-lg" onClick="EvalSound('SDJTrack2', this)"><span class="glyphicon glyphicon-play"></span>
</button>2. Song
&#13;
&#13;
&#13;