How do I play a sound when an element changes, like SO Chat does?

后端 未结 2 1136
谎友^
谎友^ 2021-02-14 07:38

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, u

2条回答
  •  感情败类
    2021-02-14 07:53

    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;
        } 
      });
    }
    

    Edit: 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.)

提交回复
热议问题