首页 > 解决方案 > 在 DIV 中滚动音频

问题描述

我想在页面的选定区域中启用音频。如果用户滚动此元素,音频将停止。我找到了这个解决方案,但问题是像素值因窗口、监视器、浏览器类型等的分辨率而不同。

var playing = false;
var audioElm = $('#soundTour').get(0);
$(window).scroll(function() {
  var pageScroll = $(window).scrollTop();
  if(!playing && pageScroll > 500 && pageScroll < 3000){
    audioElm.play();
    playing = true;
  }else if(pageScroll > 3000 || pageScroll < 500){
    audioElm.pause();
    playing = false;
  }
});
 

为此,我想在 DIV 中找到解决方案。 我的一个页面是这样的: https ://alvarotrigo.com/fullPage/examples/navigationV.html#firstPage 我希望背景声音,例如,将在第一页和第二页自动播放,并在用户时停止加入第三页。

有什么帮助吗?

标签: javascriptjquerycssaudioscroll

解决方案


在下面的代码中,当第三个块的 30% 可见时,声音开始播放。

<html>
  <head>
    <meta charset="utf-8" />
    <style>
      body { margin: 0; padding: 0; }
    </style>
  </head>
  <body>
    <audio src="/sound.wav"></audio>
    <div style="height: 100%; background: #ff5555">first page</div>
    <div style="height: 100%; background: #55ff55">second page</div>
    <div id="d3" style="height: 100%; background: #5555ff">third page</div>
    <script>
     const el = document.querySelector("audio");
     let playing = false;
     window.addEventListener('scroll', (e) => {
       const scroll = e.target.body.scrollTop;
       const rect = document.getElementById("d3").getBoundingClientRect();
       const top = rect.top;
       if (!playing && top > rect.height / 3) {
         el.play();
         playing = true;
       } else if (top < rect.height / 3) {
         el.pause();
         playing = false;
       }
     });
    </script>
  </body>
</html>

评论后更新:

<html>
  <head>
    <meta charset="utf-8" />
    <style>
      body { margin: 0; padding: 0; }
    </style>
  </head>
  <body>
    <div id="d1" style="height: 100%; background: #ff5555">first page</div>
    <div id="d2" style="height: 100%; background: #55ff55">second page</div>
    <div id="d3" style="height: 100%; background: #5555ff">third page</div>
    <script>
     const soundfiles = ["sound.wav", "sound2.wav", "sound.wav"];
     const divIds = ["d1", "d2", "d3"];
     const els = soundfiles.map((filename, index) => {
       const el = document.createElement("audio");
       el.src = "/" + filename;
       document.body.appendChild(el);
       return el;
     })
     const playing = new Array(divIds.length).fill(false);
     window.addEventListener('scroll', (e) => {
       const scroll = e.target.body.scrollTop;
       const rects = divIds.map(id => document.getElementById(id).getBoundingClientRect());
       const tops = rects.map(rect => rect.top);
       tops.forEach((top, ind) => {
         if (!playing[ind] && top <= rects[ind].height * 2 / 3 && top > - rects[ind].height * 1 / 3) {
           els[ind].play();
           playing[ind] = true;
         } else if (playing[ind] && (top > rects[ind].height * 2 / 3 || top < -rects[ind].height * 1 / 3)) {
           els[ind].pause();
           playing[ind] = false;
         }
       });
     });
    </script>
  </body>
</html>

推荐阅读