简体   繁体   English

scrollToTop不能处理jQuery(document).on('ready',function(){

[英]scrollToTop is not working on jQuery(document).on('ready', function() {

I'm trying to load my scrolltoTop() function on dom ready, but the event is not firing. 我正在尝试在dom ready上加载我的scrolltoTop()函数,但事件没有触发。 Can you please someone help me? 你能帮助别人吗?

My code is here: 我的代码在这里:

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

Here is my DOM ready function: 这是我的DOM就绪函数:

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

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

See this demo. 看这个演示。 when you run script it will scroll to top 当你运行脚本时,它将滚动到顶部

 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> 

From jquery documentation , from version 3.0 来自jquery 文档 ,从3.0版开始

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

was replaced with 被替换为

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

Maybe try: 也许试试:

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

use $(document).ready(function() {} 使用$(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> 

You need to pass the height you want to scroll to! 你需要传递你想要滚动的高度!

For example if you want to go to the start you need to pass 0. 例如,如果你想要开始,你需要传递0。

$("div").scrollTop(0);

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

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