Programmatically scroll to an Anchor Tag

前端 未结 8 1595
孤独总比滥情好
孤独总比滥情好 2020-11-28 07:21

Consider the following code:

GoTo Label2
... [content here] ...
More content


        
8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 07:46

    The solution

    document.getElementById('MyID').scrollIntoView(true);
    

    works well in almost all browsers, whereas I've noticed that in some browsers or in some mobile (such as some Blackberry versions) "scrollIntoView" function is not recognized, so I would consider this solution (a bit uglier than the previous one):

    window.location.href = window.location.protocol + "//" + window.location.host + 
                           window.location.pathname + window.location.search + 
                           "#MyAnchor";
    

提交回复
热议问题