jQuery 使用 .scroll(handler) 滚动到元素

jQuery scroll to an element using .scroll(handler)

本文关键字:滚动 元素 handler 使用 scroll jQuery      更新时间:2023-09-26

我试图在从页面顶部向下滚动一定距离后滚动到页面上的目标元素。因此,滚动到元素是由 .scroll() 事件触发的。我已经能够使用以下代码执行此操作:

$( document ).scroll( function( e ) {
    if ( $(document).scrollTop() > 250 ) {
        $('html, body').animate({
            scrollTop: $("#cy-hero-image").offset().top
        }, 650);
    }
});

但是,问题是,一旦此事件由滚动触发,页面就会粘在此滚动位置。我如何编写从页面顶部滚动时它只跳转到此页面位置一次的代码?

这是我到目前为止所拥有的JSFiddle。

您可以添加一个变量来检查它是否来自顶部。

var startsFrom = 0;
$(document).scroll(function(e) {
  if($(document).scrollTop() == 0) //you can adjust it to match whatever you want
    startsFrom = 0;
  if ($(document).scrollTop() > 250 && startsFrom == 0) {
    startsFrom = $(document).scrollTop();
    $('html, body').animate({
      scrollTop: $("#targeted-element").offset().top
    }, 650);
  }
});

https://jsfiddle.net/pdyu3f5b/14/

试试吧。每次访问页面顶部时,它都在工作。

var isScroll = true;
$(document).scroll(function(e) {
  if ($(document).scrollTop() > 250 && isScroll) {
    isScroll = false;
    $('html body').animate({
      scrollTop: $("#targeted-element").offset().top
    }, 650);
  }else if($(document).scrollTop() < 250){
    isScroll = true;
  }
});

JSFiddle

命名函数并使用.one()附加处理程序。如果未满足断点,请重新附加处理程序。

var myScrollFunc = function(e){
  if ($(document).scrollTop() > 250) {
    $('html, body').animate({
      scrollTop: $("#targeted-element").offset().top
    }, 650);
  } else {
    $(document).one('scroll', myScrollFunc);
  }
}
$(document).one('scroll', myScrollFunc);

JSFiddle

只需在使用滚动处理程序后将其删除即可

var myScroll = function( e ) {
    if ( $(document).scrollTop() > 250) {
        $('html, body').animate({
            scrollTop: $("#cy-hero-image").offset().top
        }, 650);
        $(document).off(e);
    }
});
$(document).on('scroll', myScroll);