簡體   English   中英

您可以通過JavaScript導航到瀏覽器中的錨點而不更新URL嗎?

[英]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之后:

http://www.example.com/mypage.html

您可以使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM