简体   繁体   English

单击滚动到div(在中心屏幕上显示div)

[英]Scroll to div on click (show div on center screen)

I have a question about a tiny JS that I have put at the bottom of the page. 我对页面底部的一个小型JS有疑问。 The script scrolls to another div when the user clicks on one div. 当用户单击一个div时,脚本滚动到另一个div。 On my website there is a contact button (example below). 在我的网站上有一个联系按钮(下面的示例)。

<div id="contactbutton"></div>

When the user of the website clicks on this div, the page scrolls down to another div on the page with a contact form on it (example below). 当网站的用户单击此div时,页面将向下滚动到页面上具有联系表单的另一个div(下面的示例)。

<div id="contactform">
  <form>
    (form content here)
  </form>
</div>

I did that using the following JS code at the bottom of the page, that will scroll to the other div: 我使用页面底部的以下JS代码进行了此操作,该代码将滚动到另一个div:

<script>
  $("#contactbutton").click(function() {
  $('html, body').animate({
  scrollTop: $("#contactform").offset().top
  }, 500);
  });
</script>

The code works perfect, but problem is that I have a fixed div header on my website that is on top of everything on the page. 该代码可以正常工作,但是问题是我的网站上的所有内容都位于我的网站上一个固定的div标头中。 When the user scrolls to #contactform , a part of this contact form div is behind this header. 当用户滚动到#contactform时 ,此联系表单div的一部分在此标题后面。

I am looking for a way to scroll to #contactform . 我正在寻找一种滚动到#contactform的方法 But instead of scrolling all the way, I want it to scroll till it's a certain amount of pixels away from the top of the browser window so it will show below the header and not behind it. 但是,我不想一直滚动,而是要滚动到距离浏览器窗口顶部一定距离的像素为止,这样它将显示在标题下方而不是其下方。

I hope somebody can help me out! 我希望有人能帮助我! Thanks alot in advance. 在此先感谢。

Elmigo Elmigo

You want to substract the height of your sticky header from the scroll distance, something like this ( #fixed-header is an id of your sticky header): 您想从滚动距离中减去粘性标头的高度,如下所示( #fixed-header是粘性标头的ID):

<script>
  $("#contactbutton").click(function() {
    $('html, body').animate({
      scrollTop: $("#contactform").offset().top - $('#fixed-header').outerHeight()
    }, 500);
  });
</script>

You could substract the height of your header so the scroll will stop a few pixels before your content leaving some spaces for the header 您可以减去标题的高度,以便滚动将停止几像素,然后内容才会为标题留出一些空间

<script>
  $("#contactbutton").click(function() {
  $('html, body').animate({
     scrollTop: $("#contactform").offset().top - $('#header').height()
  }, 500);
  });
</script>

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

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