如何在元素更改时播放声音,例如SO Chat吗? [英] How do I play a sound when an element changes, like SO Chat does?

查看:118
本文介绍了如何在元素更改时播放声音,例如SO Chat吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在页面上元素发生变化时播放声音。我知道如何做到这一点,但我不能让它只在第一次更改时播放,并且稍后不做,直到用户关注窗口(选项卡)并再次模糊它。

I want a sound to play when an element changes on a page. I know how to do this, but I can't get it to play only on the first change, and don't do it later, until the user focuses the window (tab) and blurs it again.

我当前的代码:

var notif = new Audio('http://cycle1500.com/sounds/infbego.wav');
if (window.innerHeight === window.outerHeight) {
  $(window).bind('DOMNodeInserted', function() {
      notif.play();
  });
}


推荐答案

使用变量来表示是否声音应该播放与否。

Use a variable to represent whether the sound should be played or not.

var shouldPlayAlertSound = true,
    notif = new Audio('http://cycle1500.com/sounds/infbego.wav');
if (window.innerHeight === window.outerHeight) {
  $(window).bind({
    'DOMNodeInserted': function() {
      if (shouldPlayAlertSound) {
        notif.play();
      }
      shouldPlayAlertSound = false;
    }, blur: function() {
      shouldPlayAlertSound = true;
    } 
  });
}

修改:在Firefox,Safari和Opera上测试了这个工作(innerHeight检查除外)。 (Chrome不支持播放WAV音频文件,仅支持MP3,AAC或Ogg Vorbis格式。)

I've tested this working on Firefox, Safari, and Opera (except for the innerHeight check). (Chrome doesn't support playing WAV audio files, only the MP3, AAC, or Ogg Vorbis formats.)

这篇关于如何在元素更改时播放声音,例如SO Chat吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆