雖然這不是函式庫的重點,htmx 確實提供了一個小型的輔助方法 API,主要用於擴充功能開發或與事件互動。
hyperscript 專案旨在為基於 htmx 的應用程式提供更廣泛的腳本支援。
htmx.addClass()
此方法將一個類別新增至給定的元素。
elt
- 要新增類別的元素class
- 要新增的類別或者
elt
- 要新增類別的元素class
- 要新增的類別delay
- 在新增類別之前的延遲時間(毫秒) // add the class 'myClass' to the element with the id 'demo'
htmx.addClass(htmx.find('#demo'), 'myClass');
// add the class 'myClass' to the element with the id 'demo' after 1 second
htmx.addClass(htmx.find('#demo'), 'myClass', 1000);
htmx.ajax()
發出 htmx 風格的 AJAX 請求。此方法會回傳一個 Promise,因此在內容插入 DOM 後可以執行回呼函數。
verb
- ‘GET’、‘POST’ 等。path
- 要發出 AJAX 請求的 URL 路徑element
- 要作為目標的元素(預設為 body
)或者
verb
- ‘GET’、‘POST’ 等。path
- 要發出 AJAX 請求的 URL 路徑selector
- 目標的選取器或者
verb
- ‘GET’、‘POST’ 等。path
- 要發出 AJAX 請求的 URL 路徑context
- 包含以下任一項的內容物件source
- 請求的來源元素,影響請求的 hx-*
屬性將針對該元素及其父元素解析event
- 「觸發」請求的事件handler
- 將處理回應 HTML 的回呼函數target
- 要將回應交換到其中的目標swap
- 相對於目標,回應將如何交換values
- 要隨請求提交的值headers
- 要隨請求提交的標頭select
- 允許您從回應中選取要交換的內容 // issue a GET to /example and put the response HTML into #myDiv
htmx.ajax('GET', '/example', '#myDiv')
// issue a GET to /example and replace #myDiv with the response
htmx.ajax('GET', '/example', {target:'#myDiv', swap:'outerHTML'})
// execute some code after the content has been inserted into the DOM
htmx.ajax('GET', '/example', '#myDiv').then(() => {
// this code will be executed after the 'htmx:afterOnLoad' event,
// and before the 'htmx:xhr:loadend' event
console.log('Content inserted successfully!');
});
htmx.closest()
在給定元素的父系中找到最接近的匹配元素,包含該元素本身
elt
- 要從中尋找選取器的元素selector
- 要尋找的選取器 // find the closest enclosing div of the element with the id 'demo'
htmx.closest(htmx.find('#demo'), 'div');
htmx.config
一個屬性,保存 htmx 在執行時使用的組態。
請注意,使用 meta 標籤是設定這些屬性的首選機制。
attributesToSettle:["class", "style", "width", "height"]
- 字串陣列:在穩定階段要穩定的屬性refreshOnHistoryMiss:false
- 布林值:如果設定為 true
,htmx 將在歷史記錄遺失時發出完整的頁面重新整理,而不是使用 AJAX 請求defaultSettleDelay:20
- 整數:完成內容交換與穩定屬性之間的預設延遲defaultSwapDelay:0
- 整數:從伺服器接收回應與執行交換之間的預設延遲defaultSwapStyle:'innerHTML'
- 字串:如果省略 hx-swap
,則要使用的預設交換樣式historyCacheSize:10
- 整數:要保留在 localStorage
中以支援歷史記錄的頁面數量historyEnabled:true
- 布林值:是否使用歷史記錄includeIndicatorStyles:true
- 布林值:如果為 true,htmx 將在頁面中注入少量 CSS,使指示器不可見,除非存在 htmx-indicator
類別indicatorClass:'htmx-indicator'
- 字串:當請求正在進行時,要放在指示器上的類別requestClass:'htmx-request'
- 字串:當請求正在進行時,要放在觸發元素上的類別addedClass:'htmx-added'
- 字串:要暫時放在 htmx 已新增至 DOM 的元素上的類別settlingClass:'htmx-settling'
- 字串:當 htmx 處於穩定階段時,要放在目標元素上的類別swappingClass:'htmx-swapping'
- 字串:當 htmx 處於交換階段時,要放在目標元素上的類別allowEval:true
- 布林值:允許在 htmx 中使用類似 eval 的功能,以啟用 hx-vars
、觸發條件和腳本標籤評估。可以設定為 false
以實現 CSP 相容性。allowScriptTags:true
- 布林值:允許在新內容中評估腳本標籤inlineScriptNonce:''
- 字串:要新增至內嵌腳本的nonceinlineStyleNonce:''
- 字串:要新增至內嵌樣式的noncewithCredentials:false
- 布林值:允許使用 cookie、授權標頭或 TLS 用戶端憑證等憑證進行跨站台存取控制請求timeout:0
- 整數:請求在自動終止之前可以花費的毫秒數wsReconnectDelay:'full-jitter'
- 字串/函式:事件代碼 Abnormal Closure
、Service Restart
或 Try Again Later
意外連線中斷後重新連線的 getWebSocketReconnectDelay
的預設實作wsBinaryType:'blob'
- 字串:透過 WebSocket 連線接收的二進位資料類型disableSelector:"[hx-disable], [data-hx-disable]"
- 字串陣列:htmx 將不會處理具有此屬性或其父系的元素scrollBehavior:'instant'
- 字串:在使用具有 hx-swap
的 show 修飾符時的捲動行為。允許的值為 instant
(捲動應在單次跳躍中立即發生)、smooth
(捲動應平滑動畫) 和 auto
(捲動行為由 scroll-behavior 的計算值決定)。defaultFocusScroll:false
- 布林值:是否應將焦點元素捲動至檢視畫面,可以使用 focus-scroll 交換修飾符覆寫getCacheBusterParam:false
- 布林值:如果設定為 true,htmx 將以 org.htmx.cache-buster=targetElementId
格式將目標元素附加到 GET
請求globalViewTransitions:false
- 布林值:如果設定為 true
,htmx 將在交換新內容時使用檢視轉換 API。methodsThatUseUrlParams:["get", "delete"]
- 字串陣列:htmx 將透過將其參數編碼在 URL 中而非請求本文中來格式化具有這些方法的請求selfRequestsOnly:true
- 布林值:是否僅允許將 AJAX 請求發送到與目前文件相同的網域ignoreTitle:false
- 布林值:如果設定為 true
,htmx 將不會在新的內容中找到 title
標籤時更新文件的標題scrollIntoViewOnBoost:true
- 布林值:是否將增強元素的目標捲動至視窗。如果在增強元素上省略 hx-target
,則目標預設為 body
,導致頁面捲動到頂端。triggerSpecsCache:null
- 物件:用於將評估的觸發規格儲存到其中的快取,以提高剖析效能,但代價是會增加記憶體使用量。您可以定義一個簡單的物件以使用永不清空的快取,或者使用Proxy 物件實作您自己的系統htmx.config.responseHandling:[...]
- HtmxResponseHandlingConfig[]:可以在此處設定預設的回應處理行為,以針對回應狀態碼進行交換或錯誤htmx.config.allowNestedOobSwaps:true
- 布林值:是否要處理主要回應元素內巢狀元素的 OOB 交換。請參閱 巢狀 OOB 交換。 // update the history cache size to 30
htmx.config.historyCacheSize = 30;
htmx.createEventSource
用於建立新的伺服器發送事件來源的屬性。可以更新此設定以提供自訂 SSE 設定。
func(url)
- 接受 URL 字串並回傳新的 EventSource
的函式 // override SSE event sources to not use credentials
htmx.createEventSource = function(url) {
return new EventSource(url, {withCredentials:false});
};
htmx.createWebSocket
用於建立新的WebSocket 的屬性。可以更新此設定以提供自訂 WebSocket 設定。
func(url)
- 接受 URL 字串並回傳新的 WebSocket
的函式 // override WebSocket to use a specific protocol
htmx.createWebSocket = function(url) {
return new WebSocket(url, ['wss']);
};
htmx.defineExtension()
定義新的 htmx 擴充功能。
name
- 擴充功能名稱ext
- 擴充功能定義 // defines a silly extension that just logs the name of all events triggered
htmx.defineExtension("silly", {
onEvent : function(name, evt) {
console.log("Event " + name + " was triggered!")
}
});
htmx.find()
尋找符合選取器的元素
selector
- 要比對的選取器或者
elt
- 要在其中尋找相符元素的根元素,包含本身selector
- 要比對的選取器 // find div with id my-div
var div = htmx.find("#my-div")
// find div with id another-div within that div
var anotherDiv = htmx.find(div, "#another-div")
htmx.findAll()
尋找所有符合選擇器的元素
selector
- 要比對的選取器或者
elt
- 要在其中尋找符合元素的根元素,包含本身selector
- 要比對的選取器 // find all divs
var allDivs = htmx.findAll("div")
// find all paragraphs within a given div
var allParagraphsInMyDiv = htmx.findAll(htmx.find("#my-div"), "p")
htmx.logAll()
記錄所有 htmx 事件,對於除錯很有用。
htmx.logAll();
htmx.logNone()
不記錄任何 htmx 事件,如果您先前已啟用除錯器,請呼叫此方法以關閉它。
htmx.logNone();
htmx.logger
htmx 用於記錄的記錄器
func(elt, eventName, detail)
- 一個函數,它接收一個元素、事件名稱和事件詳細資訊,並記錄它 htmx.logger = function(elt, event, data) {
if(console) {
console.log("INFO:", event, elt, data);
}
}
htmx.off()
從元素中移除事件監聽器
eventName
- 要移除監聽器的事件名稱listener
- 要移除的監聽器或者
target
- 要從中移除監聽器的元素eventName
- 要移除監聽器的事件名稱listener
- 要移除的監聽器 // remove this click listener from the body
htmx.off("click", myEventListener);
// remove this click listener from the given div
htmx.off("#my-div", "click", myEventListener)
htmx.on()
為元素添加事件監聽器
eventName
- 要添加監聽器的事件名稱listener
- 要添加的監聽器options
- 一個 options 物件 (或一個 useCapture 布林值),要添加到事件監聽器 (可選)或者
target
- 要添加監聽器的元素eventName
- 要添加監聽器的事件名稱listener
- 要添加的監聽器options
- 一個 options 物件 (或一個 useCapture 布林值),要添加到事件監聽器 (可選) // add a click listener to the body
var myEventListener = htmx.on("click", function(evt){ console.log(evt); });
// add a click listener to the given div
var myEventListener = htmx.on("#my-div", "click", function(evt){ console.log(evt); });
// add a click listener to the given div that should only be invoked once
var myEventListener = htmx.on("#my-div", "click", function(evt){ console.log(evt); }, { once: true });
htmx.onLoad()
為 htmx:load
事件添加回呼函式。這可用於處理新內容,例如使用 JavaScript 函式庫初始化內容
callback(elt)
- 在新載入的內容上呼叫的回呼函式 htmx.onLoad(function(elt){
MyLibrary.init(elt);
})
htmx.parseInterval()
解析與 htmx 一致的間隔字串。對於具有與計時相關屬性的外掛程式很有用。
注意:接受一個後面跟著 s
或 ms
的整數。所有其他值都使用 parseFloat
str
- 計時字串 // returns 3000
var milliseconds = htmx.parseInterval("3s");
// returns 3 - Caution
var milliseconds = htmx.parseInterval("3m");
htmx.process()
處理新內容,啟用 htmx 行為。如果您有在正常 htmx 請求週期之外新增到 DOM 的內容,但仍希望 htmx 屬性能夠運作,這會很有用。
elt
- 要處理的元素 document.body.innerHTML = "<div hx-get='/example'>Get it!</div>"
// process the newly added content
htmx.process(document.body);
htmx.remove()
從 DOM 中移除元素
elt
- 要移除的元素或者
elt
- 要移除的元素delay
- 移除元素前的延遲時間(以毫秒為單位) // removes my-div from the DOM
htmx.remove(htmx.find("#my-div"));
// removes my-div from the DOM after a delay of 2 seconds
htmx.remove(htmx.find("#my-div"), 2000);
htmx.removeClass()
從給定的元素中移除一個類別
elt
- 要從中移除類別的元素class
- 要移除的類別或者
elt
- 要從中移除類別的元素class
- 要移除的類別delay
- 移除類別前的延遲時間(以毫秒為單位) // removes .myClass from my-div
htmx.removeClass(htmx.find("#my-div"), "myClass");
// removes .myClass from my-div after 6 seconds
htmx.removeClass(htmx.find("#my-div"), "myClass", 6000);
htmx.removeExtension()
從 htmx 中移除給定的擴充功能
name
- 要移除的擴充功能名稱 htmx.removeExtension("my-extension");
htmx.swap()
執行 HTML 內容的交換(和settle)
target
- HTML 元素或交換目標的字串選擇器content
- 要交換的內容的字串表示swapSpec
- 交換規範,表示來自 hx-swap
的參數swapStyle
(必要) - 交換樣式(innerHTML
、outerHTML
、beforebegin
等)swapDelay
、settleDelay
(數字) - 分別在交換和settle之前的延遲時間transition
(布林值) - 是否使用 HTML 過渡進行交換ignoreTitle
(布林值) - 停用頁面標題更新head
(字串) - 指定 head
標籤的處理策略 (merge
或 append
)。保留空白以停用 head 處理scroll
、scrollTarget
、show
、showTarget
、focusScroll
- 指定交換後捲動處理swapOptions
- 交換的其他 *可選* 參數select
- 要交換的內容的選擇器(相當於 hx-select
)selectOOB
- 要交換帶外內容的選擇器(相當於 hx-select-oob
)eventInfo
- 要附加到 htmx:afterSwap
和 htmx:afterSettle
元素的物件anchor
- 觸發捲動的錨點元素,將在 settle 時捲動到可見。提供完整捲動處理的簡單替代方案contextElement
- 作為交換操作上下文的 DOM 元素。目前用於尋找特定元素啟用的擴充功能afterSwapCallback
、afterSettleCallback
- 分別在交換和 settle 後呼叫的回呼函式。不接收引數 // swap #output element inner HTML with div element with "Swapped!" text
htmx.swap("#output", "<div>Swapped!</div>", {swapStyle: 'innerHTML'});
htmx.takeClass()
從其同級元素中取得給定的類別,使其同級元素中只有給定元素具有該類別。
elt
- 將取得類別的元素class
- 要取得的類別 // takes the selected class from tab2's siblings
htmx.takeClass(htmx.find("#tab2"), "selected");
htmx.toggleClass()
在元素上切換給定的類別
elt
- 要在上面切換類別的元素class
- 要切換的類別 // toggles the selected class on tab2
htmx.toggleClass(htmx.find("#tab2"), "selected");
htmx.trigger()
在元素上觸發給定的事件
elt
- 要觸發事件的元素name
- 要觸發的事件名稱detail
- 事件的詳細資訊 // triggers the myEvent event on #tab2 with the answer 42
htmx.trigger("#tab2", "myEvent", {answer:42});
htmx.values()
傳回透過 htmx 值解析機制針對給定元素解析的輸入值
elt
- 要解析值的元素request type
- 請求類型(例如 get
或 post
),非 GET 請求將包含元素的封閉表單。預設為 post
// gets the values associated with this form
var values = htmx.values(htmx.find("#myForm"));