制作<a> element scroll on click to a </a> <div> <a>

时间:2017-04-21 07:33:30

标签: jquery html

I have been looking to solve this issue using some jQuery that I have found around here. I have an anchor that when clicked I want it to scroll all the way down to a div. I managed to make it scroll to the bottom of the page but this creates issues when viewing the website from mobile devices. Here is my code:

HTML

<a href="#locations" class="right-side-button"><p>I WANT TO CHOOSE A DIFFERENT COUNTRY</p></a>

<div id="locations" class="location-content">
        <h2 class="our-locations">Our locations worldwide</h2>
        <some content>
</div>

jQuery

//this is what I used to scroll to the bottom
//it does what it needs to but not good for mobile devices

$('.right-side-button').click(function(){
$('html, body').animate({ scrollTop: $(document).height()}, 'slow');});





//this is the code I am using in order to scroll to div
//for some reason it is not working when I click the anchor

var locHeight = $('main-button-section').outerHeight();
 $('.main-button-section a').click(function(e){
    e.preventDefault();
    var myHref = $(this).attr('href');
    var newPos = $(myHref).offset().top;
    $('html, body').stop().animate({scrollTop: newPos-locHeight}, 1300);
  });

1 个答案:

答案 0 :(得分:1)

你不需要做很多jQuery。动画到您的div将起作用。您可以调整其高度,以防您不想将其卡在顶部。

$("#button").click(function() {
    $('html, body').animate({
        scrollTop: $("#myDiv").offset().top - 150 /*(150) is height to leave from top*/
    }, 2000);
});