How to jump to a specified location in html

醉折花枝作酒筹
Release: 2021-06-02 16:25:02
Original
11715 people have browsed it

How to jump to a specified location in html: 1. Set the id of the container at the bottom and use # id in the href of the a tag to achieve the jump; 2. Use the window.scrollTo method, the syntax is " window.scrollTo({ top,left,behavior})".

How to jump to a specified location in html

The operating environment of this tutorial: Windows 7 system, CSS3&&HTML5 version, Dell G3 computer.

Since the information displayed on the page is always limited, we need to be able to jump to the implementation of the specified location on the page

Pure html implementation

  • Jump Turning time: Click to jump to the location named anchorName

  • Buried anchor point: Anchor point of a tag,

    Anchor point marked with id

  • Analysis : When you click the a tag, it will jump to the anchor point. There is no buffering effect, the experience is average, and "#anchorName" will be added to the url. This is unacceptable in SPA applications because it affects routing configuration. Refreshing the page has no effect.

JavaScript auxiliary (window.scrollTo method)

  • window.scrollTo({ top, left ,behavior}), respectively numbers, numbers , string. Specify the distance to jump to from the top and left of the document, and the jump effect (smooth, instant)

  • Jump timing: add event listening

  • Get the distance from the element to the top of the document (offsetTop attribute). offsetTop returns the distance of the current element relative to the top of its offsetParent element, so we need to accumulate it in a loop to get the distance from the top of the document

function heightToTop(ele){
    //ele为指定跳转到该位置的DOM节点
    let bridge = ele;
    let root = document.body;
    let height = 0;
    do{
        height += bridge.offsetTop;
        bridge = bridge.offsetParent;
    }while(bridge !== root)
 
    return height;
}
//按钮点击时
someBtn.addEventListener('click',function(){
    window.scrollTo({
        top:heightToTop(targetEle),
        behavior:'smooth'
    })
})
Copy after login

Comparing the two lines of methods, the second method is obviously better.

Recommended learning: html video tutorial

The above is the detailed content of How to jump to a specified location in html. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template