简体   繁体   English

如何在单击按钮或滚动页面时停止正在运行的功能?

[英]How can I stop a running function on a button click or page scroll?

A video autoplays on page load, and when it's finished the page automatically scrolls down to the main content container. 视频在页面加载时自动播放,完成后,页面会自动向下滚动到主要内容容器。

When a user either clicks the scroll-down button, or scrolls the page manually, I need this automatic scroll to be cancelled. 当用户单击向下滚动按钮或手动滚动页面时,我需要取消此自动滚动。

I've got the autoscroll part working. 我有自动滚动部分的工作。 I'm struggling with stopping it happening if the user interacts. 如果用户进行交互,我正在努力阻止这种情况的发生。

https://codepen.io/alexconnor/pen/bGbYgda https://codepen.io/alexconnor/pen/bGbYgda

 function scrollToMain() { $('html, body').animate({ scrollTop: ($('#main-content-container').offset().top) }, 2000); } $('#homepage-video').on('ended', function() { scrollToMain(); }); $('.arrow-scroll-down').click(function() { $('#homepage-video').off('ended', function() { scrollToMain(); }); scrollToMain(); }); $(window).scroll(function() { $('#homepage-video').off('ended', function() { scrollToMain(); }); }); 
 #video-container, #main-content-container { height: calc(100vh); } .arrow-scroll-down { font-size: 28px } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="video-container"> <video id="homepage-video" class="hp-video__video" tabindex="0" autobuffer="autobuffer" preload="preload" muted autoplay> <source src="https://v.ftcdn.net/01/93/01/28/700_F_193012896_tKFDpztvreS9PTlqINL2STlk2oxkr7na_ST.mp4" type="video/mp4; codecs=&quot;avc1.42E01E, mp4a.40.2&quot;"> </video> <div class="arrow animated bounce"> <a href="#" class="arrow-scroll-down"><i class="fas fa-chevron-down"></i></a><br /> </div> </div> <div id="main-content-container"> <h1>Main Content Container</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> 

Here's what I ended up with: 我最终得到的是:

var scrollFlag = true;

function scrollToMain() {
    $('html, body').animate({
        scrollTop: ($('#main-content-container').offset().top)
    },2000);
}

$('.arrow-scroll-down').click(function() {
  scrollFlag = false;
  scrollToMain();
});

$(window).scroll(function() {
  scrollFlag = false;
});

$('#homepage-video').on('ended',function() {
  if (scrollFlag == true) {
    scrollToMain();
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM