anchor linking to a certain position of the page

前端 未结 7 2192
渐次进展
渐次进展 2021-01-06 18:06

I have an anchor link which links to another page. When it is clicked, by default it goes to the top of the next page. I want it brought to a certain position of the page. H

7条回答
  •  北恋
    北恋 (楼主)
    2021-01-06 18:25

    here is my solution.

            $('.container').on('click', function(e){
                var hash        = $(this).find('a').attr('href'),
                    target      = $('html').find('p'+hash),
                    location    = target.offset().top;
    
                $('html, body').stop().animate({scrollTop: location}, 1000);
    
                e.preventDefault();
            });
    

    html would be like:

    
    
    

    So when clicked on the anchor it will scroll to the respective anchor in the document.

提交回复
热议问题