偏移滚动到html中? [英] offset scroll to in html?

查看:50
本文介绍了偏移滚动到html中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用html进行操作,您可以在链接上单击该链接,它会自动滚动到页面中所需的位置.这是代码的按钮/链接部分:

I am trying to do the thing in html where you click on a link and it automatically scrolls to where you want in the page. Here is the button/link part of the code:

<li><a href="#Origins">Origins</a></li>

然后将其链接到此代码表示的页面的这一部分:

And then I have it link to this part of the page represented by this code:

<h3 id="Origins">Origins</h3>

这工作得很好,但是,我在页面顶部的标题h1设置为固定位置.因此,当您单击链接时,它会向下移动到顶部标题覆盖来源"的位置页面的一部分.我尝试将填充添加到原点的顶部,这是可行的,但是之后有很多空白我不需要的页面上方来源"上方.有人有什么想法吗?预先感谢!

This works perfectly fine, however, my header of the page at the top, which is h1, is set to fixed position. So when you click the link, it goes too far down to where the header at the top is covering the "origins" part of the page. I tried adding padding to the top of origins which works but then there is a lot of blank space above "origins" in the page which I do not want. Does anyone have any ideas? Thanks in advance!

推荐答案

您可以通过滚动到 h3 减去 h1 的高度:

You could do it with Javascript(example below requires jQuery, but could also be accomplished with Vanilla Javascript) by scrolling to the position of the h3 minus the height of the h1:

$(function() {
  var h1Height = $('h1').height(); // get height of h1 tag
  $('li a').click(function (e) {
      e.preventDefault();
      var target = $(this.hash);
      $('html, body').animate({
          scrollTop: target.offset().top - h1Height // scroll to h3 minus height of h1
      }, 1000);
      return false;
  });
});

body,html {
  margin:0;
  padding:0;
}
h1{
  margin:0;
  padding:0;
  width:100%;
  background:#fff;
  position:fixed;
  top:0;
}
ul {
  margin:60px 0 0;
}
.space, h3 {
  margin:1000px 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Heading</h1>

<ul><li><a href="#Origins">Origins</a></li></ul>

<div class="space"></div>

<h3 id="Origins">Origins</h3>

这篇关于偏移滚动到html中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆