Toggle Audio Play-Pause image

后端 未结 3 725
刺人心
刺人心 2021-01-03 05:39

My html, css and js are all contained within their own files (\'index.html\', \'javascript.js\', \'style.css\'). I want to change the background-image of the button to repre

3条回答
  •  温柔的废话
    2021-01-03 06:02

    (Edit:)

    Complete example using multiple tracks

    Here's a nice example (with a really simple UI) that uses multiple tracks and Play/Pause Icons provided by FontAwesome.
    Clicking on a track will pause all ongoing audio tracks and toggle the play/pause icon for the clicked track title.
    The actual audio track src is stored in the clickable element's data-audio attribute:

    ;/*SIMPLE AUDIO PLAYER*/(function() {
      // https://stackoverflow.com/a/34487069/383904
      var AUD = document.createElement("audio"),
          BTN = document.querySelectorAll("[data-audio]"),
          tot = BTN.length;
      
      function playPause() {
        // Get track URL from clicked element's data attribute
        var src = this.dataset.audio;
        // Are we already listening that track?
        if(AUD.src != src) AUD.src = src;
        // Toggle audio play() / pause() methods
        AUD[AUD.paused ? "play" : "pause"]();
        // Remove active class from all other buttons
        for(var j=0;j
    [data-audio]{cursor:pointer;}
    [data-audio].on{color: #0ac;}
    /*https://fortawesome.github.io/Font-Awesome/cheatsheet/*/
    [data-audio]:before{content:"\f144";}
    [data-audio].on:before{content:"\f28b";}
    
    
    
       ACDC: Back in Black
    Metallica:Enter Sandman
    U2: One


    (Actual Answer:)

    1. Don't use inline JS, keep your JS logic in one place
    2. Use addEventListener and the correct camelCase style.backgroundImage (or style["background-image"] if you will)
    3. (Button is already a "type=button")

    
    

    var losAudio = document.getElementById("losAudio");
    
    function losAudio_playPause() {
        var isPaused = losAudio.paused;
        losAudio[isPaused ? "play" : "pause"]();
        this.style.backgroundImage="url('img/"+ (isPaused ? "icoPlay" : "icoPause") +".png')";
    }
    
    document.getElementById("btn_playPause").addEventListener("click", losAudio_playPause);
    

    Don't request new images on click! Use a CSS Sprite Image for your element:

    and change it's background-position on click:

    var audio = document.getElementById("losAudio");
    var btn_playPause = document.getElementById("btn_playPause");
    
    function losAudio_playPause() {
      var isPaused = losAudio.paused;
      losAudio[isPaused ? "play" : "pause"]();
      this.style.backgroundPosition= "0 "+ (isPaused ? "-32px":"0px");
    }
    
    btn_playPause.addEventListener("click", losAudio_playPause);
    #btn_playPause{
      background:url(http://i.stack.imgur.com/ENFH5.png) no-repeat;
      border:none;
      width:32px;
      height:32px;
      cursor:pointer;
      outline:none;
    }
    
    

提交回复
热议问题