简体   繁体   中英

Play sound when <div> is visible

I have a delayed display div. I want to add sound when div is visible. How can I do this?

 $(document).ready(function(){ $(".deley").hide(); setTimeout(function () { $(".deley").show(); }, 5000); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="deley">TEXT</div> 

 $(document).ready(function(){ $(".deley").hide(); setTimeout(function () { $(".deley").show(); $(".audioPlayer")[0].play(); }, 5000); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="deley">TEXT</div> <audio class="audioPlayer"> <source src="horse.ogg" type="audio/ogg"> <source src="http://op.50megs.com/house!.wav" type="audio/wav"> </audio> 

The simplest way would be to include it in whatever event listener you're using to toggle the element's display value.

When hiding (ie $(".deley").hide(); :

    $("#epicSound").pause();
    $('#epicSound").currentTime = 0;

When showing (ie $('.deley').show() ):

    $("#epicSound").play();

Your code:

<script type="text/javascript">
$(document).ready(function(){
    $(".deley").hide();
    // if sound is currently playing, stop it and reset
    if(!$("#epicSound").paused) {
        $("#epicSound").pause();
        $("#epicSound").currentTime = 0;
    }
    setTimeout(function () {
        $(".deley").show();
        $("#epicSound").play();            
    }, 5000);
});
</script>
<div class="deley">TEXT</div>
<audio id="epicSound">
  <source src="epicSound.ogg" type="audio/ogg">
  <source src="epicSound.mp3" type="audio/mpeg">
</audio>

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