Anchor point positioning - how to set the distance between the anchor point and the top of the page, the anchor point positioning and a certain offset from the top

Anchor point is a type of hyperlink in web page production, also called named anchor. A named anchor is a hyperlink within a page, like a quick locator, and is widely used.

Named anchors allow you to set markup in a document, usually at or at the top of a specific topic in the document. Links to these named anchors can then be created that quickly take visitors to the specified location.

Creating a link to a named anchor is a two-step process. First, create a named anchor, and then create a link to the named anchor.

1. Ordinary anchor point

<a href="#aboutmao" >锚点链接</a>

...


<div id="aboutmao">锚点跳转到这里</div>

These are perfect anchor functions, but if the header of my web page is always fixed at the top, this is the distance that the anchor link needs to be at the top of a header, otherwise the content of the linked link will be blocked by the header.

For example:
Insert image description here
The effect we want:
Insert image description here
It is most convenient to solve this problem with js:

<a href="javascript:;" class="aboutmao">关于我们</a>

<div id="about">锚点跳转到这里</div>

<script>
    $(document).ready(function () {
      
      

      function topMao(target) {
      
      
        $('html, body').animate({
      
      
          scrollTop: $(target).offset().top - $('.topnav').height() //顶部固定导航
        }, 500); //130为锚点到距顶部的距离,500为执行时间
        return false;
      }

      $('.aboutmao').click(function () {
      
      
        topMao('#about');
      }) 

    })
  </script>

Click the event of the anchor point, then get the distance of this id from the top of the web page, subtract the height of the header, and finally use window.scrollTo to directly slide to the anchor point position. It has been tested OK on IE10+, Firefox, and Google Chrome.

Guess you like

Origin blog.csdn.net/ws19900201/article/details/123905368