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})".
The operating environment of this tutorial: Windows 7 system, CSS3&&HTML5 version, Dell G3 computer.
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' }) })
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!