单击按钮背景更改

时间:2013-04-21 03:48:58

标签: javascript html

我正在尝试为我的HTML5音频播放器创建自定义控件。

目前,我有我的播放/暂停按钮,但是,在点击的按钮上,我想将当前的播放背景更改为暂停符号。

JS工作得很好,只是无法弄清楚如何切换背景。

HTML5:

<div id="myButtons">
<button id="playpause" title="play" onclick="togglePlayPause()"></button>
<input id="volume" min="0" max="1" step="0.1" type="range" onchange="setVolume()" />
<button id="mute" onclick="toggleMute()">Mute</button>
</div>

使用Javascript:

function togglePlayPause() {
   var playpause = document.getElementById("playpause");
   if (audio.paused || audio.ended) {
      playpause.title = "";
      playpause.innerHTML = "";
      audio.play();
   }
   else {
      playpause.title = "";
      playpause.innerHTML = "";
      audio.pause();
   }

3 个答案:

答案 0 :(得分:1)

试试这个

function togglePlayPause() {

       var playpause = document.getElementById("playpause");

       if (audio.paused || audio.ended) {
          playpause.style.backgroundImage="url(play.png)";
          playpause.title = "";
          playpause.innerHTML = "";
          audio.play();
       }
       else {
          playpause.style.backgroundImage="url(pause.png)";
          playpause.title = "";
          playpause.innerHTML = "";
          audio.pause();
       }
}

答案 1 :(得分:1)

如果你只是添加一些类可能会更好:

.button-icon-play {
  background: url(...) /*other background styling stuff*/;
}

.button-icon-pause {
  background: url(...) /*other background styling stuff*/;
}

默认情况下将button-icon-play添加到您的元素中,然后在您的JS中添加:

/*Switch to pause button*/
playpause.className = 'button-icon-pause';

/*Switch to play button*/
playpause.className = 'button-icon-play';

答案 2 :(得分:0)

您可以使用jquery

设置css值
var playpause = $("#playpause");
var foo = false;

    playpause.click(function(){
        if(foo===false){
        playpause.css("background", pause-background-url);
         foo=true;
        }
        else{
          foo=false;
         playpause.css("background", play-background-url);
        }
    }};