Scrolling page action without click function in ht

2019-08-13 00:25发布

问题:

I am using this code to scroll the page after clicking a button:

$(document).ready(function() {
  $("#button").click(function(e) {
    e.preventDefault();
    $('html, body').animate({
      scrollTop: $($.attr(this, 'href')).offset().top
    }, 8000);
  });
});

But I want to make it work without clicking any button. When the page loads, it should scroll. I used this code and it does not work:

$(document).ready(function() {
  $('html, body').animate({
    scrollTop: $($.attr(this, 'href')).offset().top
  }, 8000);
});

回答1:

I personally am not a big fan of using jQuery's animate function, so i implemented my own. You can change the speed of it by increasing or decreasing the time of the setTimeout function.

$(document).ready(function() {
    var pixels = $('a').position();
    Scroll(pixels.top);
});

function Scroll(pixels) {
    if( pixels > 0){
        window.scrollBy(0,1);
        scrollTimeout = setTimeout(function(){
            Scroll(pixels-1); 
        },1);
    }
    else {
        clearTimeout(scrollTimeout)
        return;
    }
}

Here is a link to the fiddle that i made to demonstrate what I think you are trying to do. Let me know if this helps!

https://jsfiddle.net/ogb4t33q/



回答2:

In this block:

$(document).ready(function(){  
  $('html, body').animate({
    scrollTop: $($.attr(this, 'href')).offset().top
  }, 8000);
});

this will refer to document. That was OK in the other version of your function, because this referred to an <a> element with href. That allowed $($.attr(this, 'href')) to find an element and complete the logic to scroll there.

You'll either need to define exactly the element you want to scroll to like this:

$(document).ready(function() {
  $('html, body').animate({
    scrollTop: $('#scrollToThisEl').offset().top
  }, 3000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div style="height:3000px;background:repeating-linear-gradient(0deg,#606dbc,#606dbc 50px,#465298 50px,#465298 100px);"></div>
<div id="scrollToThisEl">Scroll here</div>
<div style="height:3000px;"></div>

Or work with window.location.hash to read the #... value from the URL.

$(document).ready(function(){  
  $('html, body').animate({
    scrollTop: $(window.location.hash).offset().top
  }, 3000);
});