简体   繁体   中英

Link to paragraph on same page

I've created a link to a certain paragraph. So when I click my button, I go to the paragraph on that same page.

Button:

<a href="http://example.com/#paintings">Paintings</a>

Link to paragraph:

<a name="paintings"><h2>Paintings</h2></a>

My problem is that I want to adjust the view after clicking the link. What I actually wanna do is:

  1. Click Button
  2. Go to the paragraph
  3. Scroll down 40px

Is there a simple way to achieve this?

只需将<a name="paintings">更改为<a id="paintings">

<a id="paintings"><h2>Paintings</h2></a>

I fixed it by using jQuery.

var element = document.getElementById(page);
var rect = element.getBoundingClientRect();
var elementLeft,elementTop;
var scrollTop = element.scrollTop?
element.scrollTop:document.body.scrollTop;
elementTop = rect.top+(scrollTop);
var menuBar = $('#header').height();

$("html, body").animate({
    scrollTop: (elementTop -menuBar)
}, 1000 / 2);

This will make my page scroll down to the element. He will calculate the height of the element in my html and substract the height of my menu bar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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