只有当div可见时播放声音文件?

时间:2013-12-09 18:54:05

标签: jquery html5 audio

我使用jquery在3秒后淡入div。我现在要做的是设置一个if语句来说明当div“dashboard_right2”可见时播放声音片段。

目前我正在使用这个html5音频脚本启动在页面加载时播放的声音文件,但是我想声音文件仅在div“dashbaord_right2”可见时播放。有人可以告诉我该怎么做,谢谢。

音频代码:

<audio src="assets/music/sound_file.mp3" autoplay>
</audio>
<script>
var audio = document.createElement("audio");
if (audio != null && audio.canPlayType && audio.canPlayType("audio/mpeg"))
{
audio.src = "audio/sample.mp3";
audio.play();
}
</script>
<audio src="data:audio/mpeg,ID3%02%00%00%00%00%..." autoplay>
</audio>

div使用jquery在3秒后淡入:

<script>
$('.dashboard_right2').hide(); // this or use css to hide the div
$('.dashboard_right2').delay(2000).fadeIn('slow');
</script>

1 个答案:

答案 0 :(得分:0)

你可以这样做:

$('.dashboard_right2').delay(2000).fadeIn('slow', function() {
  // play your audio
  audio.play();
});

$('.dashboard_right2').hide();
audio.pause();

例如:

<div id="toggleMusic">Toggle Music</div>

<audio id="audio" src="assets/music/sound_file.mp3" autoplay>

<script type="text/javascript">
$("#toggleMusic").click(function() {
   var audio = document.getElementsByTagName('audio')[0];

   if($(".dashboard_right2").is(":visible")) {
      // hide the dashboard and pause the music
      $('.dashboard_right2').hide();
      audio.pause();
   } else {
      // show the dashboard and start the music
      $('.dashboard_right2').delay(2000).fadeIn('slow', function() {
         audio.play();
      });
   }
});
</script>

如果您只需要在页面加载fadeIn(),那么您应该使用toggle()方法隐藏/显示您的元素:

$('.dashboard_right2').toggle(0, function() {
   if($('.dashboard_right2').is(':visible')) {
      audio.play();
   } else {
      audio.pause();
   }
});