![](/img/trans.png)
[英]Navigate with anchor without changing browser url and without javascript
[英]Can you navigate to an anchor in the browser via JavaScript without updating the URL?
JavaScript瀏覽器中是否有一種方法可以用來導航到頁面上的錨點,但不更新URL片段?
例如,
HTML:
<h1 id="GettingStarted">Getting Started</h1>
JavaScript的:
var anchor = "Getting Started";
window.scrollToHTMLElement(anchor);
我不想更新URL片段。
之前的網址:
http://www.example.com/mypage.html
URL之后:
您可以使用scrollIntoView
document.getElementById('GettingStarted').scrollIntoView();
要么
document.getElementById('GettingStarted').scrollIntoView({
behavior: 'smooth'
});
如果您想要平滑的動畫。
查看這個小提琴作為示例。
正如喬納森· scrollIntoView()
Jonathan Heindl)指出的那樣, scrollIntoView()
可以解決您的問題。 更具體地講,你將有你想要去一個元素,一個按鈕(或任何你想要的,只是不是a
標簽):
<h1 id="GettingStarted">Getting Started</h1>
<button type="button" id="trigger">Go</button>
然后是一些簡單的javascript代碼:
document.getElementById('trigger').addEventListener('click', function(){
var anchor = document.getElementById('GettingStarted');
anchor.scrollIntoView();
})
示例結果如下:
document.getElementById('trigger').addEventListener('click', function(){ var anchor = document.getElementById('GettingStarted'); anchor.scrollIntoView(); })
<h1 id="GettingStarted">Getting Started</h1> <div style="min-height: 150vh"></div> <button type="button" id="trigger">Go</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.