简体   繁体   中英

Javascript: play/pause if clicked and change src

HTML

<audio id="player" src="file.ogg"></audio>
<img id="playpause" src="play.png" />

JAVASCRIPT

playpause.addEventListener('click', function () {
    document.getElementById('player').play();
    this.src = 'pause.png';
});

Here's what I have so far. I'd like to alternatively play ( document.getElementById('player').play() ) and pause ( document.getElementById('player').pause() ) the song when you click on #playpause and also change the src when playing ( play.png ) and pausing ( pause.png ).

I can use jQuery but simple Javascript I think is enough.

How about a flag variable?

var playing = false;
playpause.addEventListener('click', function () {
    if(!playing) {
        document.getElementById('player').play();
        this.src = 'pause.png';
    }
    else {
        document.getElementById('player').pause();
        this.src = 'play.png';
    }
    playing = !playing;
});

Use the paused property of the player element.

var player = document.getElementById('player');

playpause.addEventListener('click', function () {
    player[player.paused ? "play" : "pause"]();
    this.src = (player.paused ? "pause" : "play") + ".png";
});

HTML

<audio id="player" src="file.ogg" data-state="0"></audio>
<img id="playpause" src="play.png" />

JS

playpause = document.getElementById( 'playpause' );
audio = document.getElementById( 'player' );

playpause.addEventListener('click', function() {
    (player.dataset.state === '0') ? player.play() : player.pause(); player.dataset.state = '1';
});

Please note this is untested. Good Luck!

You can use 'paused' property of the Audio tag.

playpause.addEventListener('click', function () {
 var player = document.getElementById('player');
 if(player.paused){
   player.play();
   this.src = 'pause.png';
 }else{
   player.pause();
   this.src = 'play.png';
 }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM