hx-swap

hx-swap 屬性允許您指定相對於 AJAX 請求的目標,如何替換回應。如果您未指定選項,則預設值為 htmx.config.defaultSwapStyle (innerHTML)。

此屬性的可能值為:

這些選項基於標準 DOM 命名和 Element.insertAdjacentHTML 規範。

因此,在以下程式碼中:

  <div hx-get="/example" hx-swap="afterend">Get Some HTML & Append It</div>

div 將向 /example 發出請求,並將傳回的內容附加到 div 之後

修飾符

hx-swap 屬性支援用於更改替換行為的修飾符。它們概述如下。

轉換:transition

如果您想在發生替換時使用新的 View Transitions API,您可以為您的替換使用 transition:true 選項。您也可以將 htmx.config.globalViewTransitions 配置設定設為 true 來全域啟用此功能。

時序:swap & settle

您可以透過包含 swap 修飾符來修改 htmx 在收到回應後等待替換內容的時間量

  <!-- this will wait 1s before doing the swap after it is received -->
  <div hx-get="/example" hx-swap="innerHTML swap:1s">Get Some HTML & Append It</div>

類似地,您可以透過包含 settle 修飾符來修改替換和 settle 邏輯之間的時間

  <!-- this will wait 1s before doing the swap after it is received -->
  <div hx-get="/example" hx-swap="innerHTML settle:1s">Get Some HTML & Append It</div>

這些屬性可用於將 htmx 與 CSS 轉換效果的時間同步。

標題:ignoreTitle

預設情況下,如果 htmx 在回應內容中找到 <title> 標籤,它會更新頁面的標題。您可以將 ignoreTitle 選項設為 true 來關閉此行為。

捲動:scroll & show

您還可以透過使用 scrollshow 修飾符來變更目標元素的捲動行為,這兩個修飾符都接受值 topbottom

  <!-- this fixed-height div will scroll to the bottom of the div after content is appended -->
  <div style="height:200px; overflow: scroll" 
       hx-get="/example" 
       hx-swap="beforeend scroll:bottom">
     Get Some HTML & Append It & Scroll To Bottom
  </div>
  <!-- this will get some content and add it to #another-div, then ensure that the top of #another-div is visible in the 
       viewport -->
  <div hx-get="/example" 
       hx-swap="innerHTML show:top"
       hx-target="#another-div">
    Get Some Content
  </div>

如果您希望針對不同的元素進行捲動或顯示,您可以在 scroll:show: 之後放置 CSS 選擇器,後接 :top:bottom

  <!-- this will get some content and swap it into the current div, then ensure that the top of #another-div is visible in the 
       viewport -->
  <div hx-get="/example" 
       hx-swap="innerHTML show:#another-div:top">
    Get Some Content
  </div>

您也可以使用 window:topwindow:bottom 來捲動到目前視窗的頂部和底部。

  <!-- this will get some content and swap it into the current div, then ensure that the viewport is scrolled to the
       very top -->
  <div hx-get="/example" 
       hx-swap="innerHTML show:window:top">
    Get Some Content
  </div>

對於加強連結和表單,預設行為是 show:top。您可以使用 htmx.config.scrollIntoViewOnBoost 全域停用它,或者您可以在元素基礎上使用 hx-swap="show:none"

<form action="/example" hx-swap="show:none">
  ...
</form>

焦點捲動

htmx 會在請求之間保留具有已定義 id 屬性的輸入的焦點。預設情況下,htmx 會防止在請求之間自動捲動到已聚焦的輸入,當使用者已經捲動離開時,這可能是較長請求中不想要的操作。若要啟用焦點捲動,您可以使用 focus-scroll:true

  <input id="name" hx-get="/validation" 
       hx-swap="outerHTML focus-scroll:true"/>

或者,如果您希望頁面在每次請求後自動捲動到焦點元素,您可以將 htmx 全域配置值 htmx.config.defaultFocusScroll 變更為 true。然後,使用 focus-scroll:false 為特定請求停用它。

  <input id="name" hx-get="/validation" 
       hx-swap="outerHTML focus-scroll:false"/>

注意事項