简体   繁体   English

链接到同一页面上的段落

[英]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 向下滚动40像素

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. 我使用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. 他将计算html中元素的高度,然后减去菜单栏的高度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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