簡體   English   中英

在不重新加載的情況下在頁面內跳轉要聽什么事件?

[英]What is the event to listen to for jumping within page without reloading?

我正在寫一個小文檔, html 就像:

<dl class="commands">
  <dt id="commandA">Command A</dt>
  <dd class="description">This command makes you happy.</dd>
  <dt id="commandB">Command B</dt>
  <dd class="description">This command makes you even happier.</dd>
</dl>

我認為如果訪問mydoc.html#commandA會很好地突出顯示command A的描述的位置,並編寫以下 JavaScript:

(function(){
  window.addEventListener('load', emphCmd);
  
  function emphCmd(){
    var loc = window.location.href;
    if (/\.html#.*$/.test(loc)){
      var cmd = loc.split("#")[1]; // "commandA" for mydoc.html#commandA
      var cmdElm = document.getElementById(cmd);
      if (cmdElm !== null){ // if element with that id is found,
        cmdElm.style.backgroundColor = "#eeeeaa"; // highlight its background.
      }
    }
  }
})();

這有效,但僅在頁面加載時(當然。我說在load時執行此操作)。 該腳本不執行任何操作的情況包括:i) 當我手動將#commandA添加到瀏覽器的地址欄中並按 Enter 時(沒有F5 --- 重新加載)ii) 在帶有<a>標記的頁面內跳轉。

我希望在任何一種情況下都突出顯示它。 對於<a href="#commandA"> ,我可能會anchor.addEventListener('click',emphCmd) ,雖然這看起來不是很整潔。

這些“在頁面內跳轉”是否有事件? 如果沒有,有什么好的方法可以達到這種效果?

沒有一個事件可以涵蓋您的用例,但由於您只是嘗試設置目標元素的樣式,因此您實際上可以利用:target CSS 偽類。 MDN 文檔有一個很好的描述和一些例子:

帶有片段標識符的 URI 鏈接到文檔中的某個元素,稱為目標元素。 例如,這是一個指向名為 section2 的錨點的 URI: http://example.com/folder/document.html#section2錨點可以是任何具有 id 屬性的元素,例如<h1 id="section2"> in我們的例子。 目標元素 h1 可以由:target 偽類表示。

:target偽類也適用於命名錨(即<a name="some-id-value"></a> ),因此它與舊標記向后兼容。 但是,您會注意到,使用命名錨點並不是100% 相同 - 目標項目接收規則,而錨點是內聯元素。

這是@KingKing 的示例,包含在代碼片段中:

 :target { background: #eeeeaa; }
 <a href="#commandA">Command A</a> <a href="#commandB">Command B</a> <a href="#commandC">Command C</a> <dl class="commands"> <dt id="commandA">Command A</dt> <dd class="description">This command makes you happy.</dd> <dt id="commandB">Command B</dt> <dd class="description">This command makes you even happier.</dd> <dt><a name="commandC">Command C</a></dt> <dd class="description">This command makes you sad, since it's using a named anchor.</dd> </dl>

一個警告是 IE8 及以下不支持:target選擇器。 你可以通過使用諸如SelectivirIE9.js 之類的 polyfill 來解決這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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