scrollToTop 在 jQuery(document).on('ready', function() {



我正在尝试在 dom ready 上加载我的 scrolltoTop() 函数,但事件没有触发。你能请别人帮我吗?

我的代码在这里:

<button class="scroll-top">
<i class="fa fa-angle-up" aria-hidden="true"></i>
</button>

"use strict";
function scrollToTop () {
  if ($('.scroll-top').length) {
    $(window).on('scroll', function (){
      if ($(this).scrollTop() > 200) {
        $('.scroll-top').fadeIn();
      }
      else {
        $('.scroll-top').fadeOut();
      }
    });
    $('.scroll-top').on('click', function() {
      $('html, body').animate({scrollTop : 0},1500);
      return false;
    });
  }
}

这是我的 DOM 就绪函数:

jQuery(document).on('ready', function() {
  (function ($) {
    scrollToTop ();
  })(jQuery);
});

使用 Jquery 版本: jquery-3.4.1.min.js

使用$(document).ready(function() {}

"use strict";
function scrollToTop() {
  console.log('Calling');
  if ($('.scroll-top').length) {
    $(window).on('scroll', function() {
      console.log($(this).scrollTop());
      if ($(this).scrollTop() > 200) {
        $('.scroll-top').fadeIn();
      } else {
        $('.scroll-top').fadeOut();
      }
    });
    $('.scroll-top').on('click', function() {
      $('html, body').animate({
        scrollTop: 0
      }, 1500);
      return false;
    });
  }
}
$(document).ready(function() {
  scrollToTop();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="scroll-top">
   <i class="fa fa-angle-up" aria-hidden="true"></i>
</button>

请参阅此演示。 当您运行脚本时,它将滚动到顶部

jQuery(document).on('ready', function() {
  $(window).scrollTop(0);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="border:1px solid black;width:100px;height:150px;overflow:auto">
This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text.</div><br>

来自 jquery 文档 ,来自版本 3.0

$( document ).ready(function() {
  // Handler for .ready() called.
});

被替换为

$(function() {
   // Handler for .ready() called.
});

也许尝试:

$(function() {
   window.scrollTo(0,0);
});

最新更新