Audio on scroll

只愿长相守 提交于 2019-11-30 14:23:14

问题


I'm doing a website with the skrollr plugin and I'm almost done with the pictures and scrolling itself, so I'm trying to add the audio now, but I can't seem to make the audio start and stop when I want it to. This is the script I am currently working with:

<script>

$(window).scroll(function() {
    var height = $(document).height() - $(window).height();
var scroll = $(window).scrollTop();  
      var audioElm = $('#soundTour').get(0);
    audioElm.play();
    audioElm.volume = 1 - $(window).scrollTop()/height;
    console.log(audioElm.volume);
});
</script>

This makes my audio start as soon as the website is loaded and fade out across the span of the entire website, so when you've scrolled to the bottom, it's completely silent. I've tried messing with the "height" variable in the script, but to no avail. The sound always ends up heavily lowered, but still faintly playing in the background. Is there a way to make it shut up at a certain scroll point? For example, make the audio play at $(window).scrollTop() = 500 and stop at $(window).scrollTop() = 3000?


回答1:


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

You need to add some conditions. (I define the variables outside for performance matters, as jQuery scroll has really bad performance, that gets even worse on phones).

Pen: http://codepen.io/vandervals/pen/KpWzVJ



来源:https://stackoverflow.com/questions/30598817/audio-on-scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!