Four methods to achieve anchor location and jump in html page

Posted by flash-genie on Tue, 01 Mar 2022 10:24:53 +0100

The method of clicking the jump anchor often appears in the project, such as giving an a tag a href = "# anchor", and then giving an id = "anchor" to the anchor to jump, so as to realize a simple jump, but in this way, an example such as www.geekjc.com will appear behind the url address bar COM / # anchor, and then you click back once to return to the url of the last selected anchor. Here are four methods to jump to the anchor.

The first method

  • It is also the simplest method to write the id of div in the href attribute with the anchor tag. as follows
<style>  
    div {  
        height: 800px;  
        width: 400px;  
        border: 2px solid black;  
    }  
    h2 {  
        position: fixed;  
        margin:50px 500px;  
    }  
</style>  
  
  
<h2>  
    <a href="#div1">to div1</a>  
    <a href="#div2">to div2</a>  
    <a href="#div3">to div3</a>  
</h2>  
    <div id="div1">div1</div>  
    <div id="div2">div2</div>  
    <div id="div3">div3</div>  

The disadvantage of this method is that after clicking the anchor point, the browser URL will change, and there may be problems if it is refreshed.

The second method

  • Is passed in the js event
  window.location.hash="divId"
  • Jump, but the address will also change. It feels no different from the first method, even more troublesome.

The third method

  • The animation attribute is used. After clicking the anchor point, the page will scroll to the corresponding DIV. Next, add the following code to the above code:
$(document).ready(function() {
    $("#div1Link").click(function() {
        $("html, body").animate({
            scrollTop: $("#div1").offset().top }, {duration: 500,easing: "swing"});
            return false;
    });
    $("#div2Link").click(function() {
        $("html, body").animate({
        scrollTop: $("#div2").offset().top }, {duration: 500,easing: "swing"});
        return false;
    });
    $("#div3Link").click(function() {
        $("html, body").animate({
        scrollTop: $("#div3").offset().top }, {duration: 500,easing: "swing"});
        return false;
    });
});

Note: before running the above script, add the corresponding id to the anchor and remove the href attribute. $("html, body") can be replaced by the response div. if it doesn't work, try adding the overflow: scroll attribute to the div. In addition, the script can be further optimized. Try it yourself. The advantage of this is that the URL address will not change. At the same time, when you click the anchor point, it will automatically respond to the scroll event without rebinding. The disadvantage is that if the page is complex, the offset value may change, which requires algorithm assistance.

The fourth method

  • The srollIntoView method of js is used directly:
document.getElementById("divId").scrollIntoView();

//For example:

document.querySelector("#roll1").onclick = function(){
      document.querySelector("#roll1_top").scrollIntoView(true);
}  
  • Here, click the element whose id is #roll1 to scroll to the element whose id is #roll1_top place, here #roll1 and #roll1_top should be one-to-one. The advantage of this method is that the URL will not change, and it can respond to the corresponding scroll event without algorithms. The code is as follows:
<html>
    <head>
        <title>HTML5_ScrollInToView method</title>
        <meta  charset="utf-8">
        <style type="text/css">
            #myDiv{
                height:900px;
                background-color:gray;

            }
            #roll_top{
                height:900px;
                background-color:green;
                color:#FFF;
                font-size:50px;
                position:relative;
            }
            #bottom{
                position:absolute;
                display:block;
                left;0;bottom:0;
            }
        </style>
    </head>
    <body>
        <button id="roll1">scrollIntoView(false)</button>
        <button id="roll2">scrollIntoView(true)</button>
        <div id="myDiv"></div>
        <div id="roll_top">
            scrollIntoView(ture)The top border of the element is flush with the top of the window
            <span id="bottom">scrollIntoView(false)The lower border of the element is flush with the bottom of the window</span>
        </div> 
    </body>
</html>
  • javascript part
window.onload = function(){
    /*
        If scrolling pages is also a problem that DOM does not solve. To solve this problem, the browser implements the following methods,
    To facilitate developers how to better control the scrolling of the page. Among various proprietary methods, HTML5 selects scrollIntoView()
    As a standard method.
        scrollIntoView()It can be called on all HTML elements by scrolling the browser window or a container element,
    The calling element can appear in the window. If true is passed as a parameter to the method, or no parameter is passed, then
    After the window scrolls, the top of the transfer element and the top of the window will be as flush as possible. If false is passed as a parameter, the element is called
    It appears as completely as possible in the viewport (if possible, the bottom of the calling element is flush with the top of the viewport.) But the top
    Not necessarily flush, for example:
    //Make elements visible
    document.forms[0].scrollIntoView();
    When the page changes, this method is generally used to attract users' attention. In fact, setting focus for an element is also useful
    Causes the browser to scroll through the elements that get focus.
        Browsers supporting this method include IE, Firefox, Safari and Opera.
    */

    document.querySelector("#roll1").onclick = function(){
        document.querySelector("#roll_top").scrollIntoView(false);
    }
    document.querySelector("#roll2").onclick = function(){
        document.querySelector("#roll_top").scrollIntoView(true);
    }
}

To sum up, the third and fourth methods are the most recommended.

The specific code is as follows:

<div class="fix-bar-box" id="div_assertErr">
    <div class="fix-bar">
		<button type="button"  onclick="viewErrInfo();" class="frm-button-blue"/>View error messages</button>
	</div>
</div>

<script type="text/javascript">
var relationErrInfo=0;
function viewErrInfo() {
		$("html,body").animate({scrollTop: $($(".relationTradeErr")[relationErrInfo]).offset().top}, 800);
		var size=$(".relationTradeErr").length;
		if(relationErrInfo < size-1){
			relationErrInfo++;
		}else {
			relationErrInfo=0;
		}
	}
</script>

Code interpretation: usage scenario - there are multiple relationtradeerrs on the page. Jump to the corresponding position according to the custom class attribute (relationTradeErr) and display it at the top of the page. Click again to jump to the next error message.

If there is only one, it can be adjusted as follows:

function viewErrInfo() {
	$("html,body").animate({scrollTop: $(".relationTradeErr").offset().top}, 800);
}

Topics: Javascript Front-end html