Home>Article>Web Front-end> How to jump to a specified location in html
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: b080426733c89407a25a10de72aa5ac4Click to jump to the location named anchorName5db79b134e9f6b82c0b36e0489ee08ed
Buried anchor point: ca61919265dda2d9942a53ed98c4ef6aAnchor point of a tag5db79b134e9f6b82c0b36e0489ee08ed, 95c52d768b99697aaa329aa31a992079Anchor point marked with id94b3e26ee717c64999d7867364b1b4a3
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!