Scrolling page action without click function in ht

2019-08-12 23:35发布

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

2条回答
Animai°情兽
2楼-- · 2019-08-13 00:30

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/

查看更多
劳资没心,怎么记你
3楼-- · 2019-08-13 00:38

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);
});
查看更多
登录 后发表回答