許多 CSS 工具組都包含用於建立模態對話框的樣式(和 Javascript)。這個範例示範如何使用 HTMX 來顯示使用 UIKit 的動態對話框,以及如何用少量或無需 Javascript 來觸發其動畫樣式。
我們從一個觸發對話框的按鈕開始,以及在您的標記底部的 DIV,對話框將被載入到該 DIV 中。
這是一個使用 HTMX 遠端載入使用 UIKit 的模態對話框的範例。在這個範例中,我們將使用 Hyperscript 來示範該腳本語言如何乾淨俐落地將 htmx 和其他函式庫結合在一起。
<button
id="showButton"
hx-get="/uikit-modal.html"
hx-target="#modals-here"
class="uk-button uk-button-primary"
_="on htmx:afterOnLoad wait 10ms then add .uk-open to #modal">Open Modal</button>
<div id="modals-here"></div>
當點擊此按鈕時,此按鈕會使用 GET
請求到 /uikit-modal.html
。此檔案的內容將被新增到 #modals-here
DIV 下面的 DOM 中。
我們沒有使用標準的 UIKit Javascript 函式庫,而是使用一點 Hyperscript,它會觸發 UIKit 的流暢動畫。它會延遲 10 毫秒,以便 UIKit 的動畫可以正確執行。
最後,伺服器會回應用稍微修改過的 UIKit 標準模態視窗。
<div id="modal" class="uk-modal" style="display:block;">
<div class="uk-modal-dialog uk-modal-body">
<h2 class="uk-modal-title">Modal Dialog</h2>
<p>This modal dialog was loaded dynamically by HTMX.</p>
<form _="on submit take .uk-open from #modal">
<div class="uk-margin">
<input class="uk-input" placeholder="What is Your Name?">
</div>
<button type="button" class="uk-button uk-button-primary">Save Changes</button>
<button
id="cancelButton"
type="button"
class="uk-button uk-button-default"
_="on click take .uk-open from #modal wait 200ms then remove #modal">Close</button>
</form>
</div>
</div>
按鈕和表單上的 Hyperscript 會在完成或取消對話框時觸發動畫。如果您不使用此 Hyperscript,模態視窗仍然可以運作,但不會觸發 UIKit 的淡入動畫。
當然,您可以使用 JavaScript 而不是 Hyperscript 來完成這項工作,但它需要更多的程式碼。
// This triggers the fade-in animation when a modal dialog is loaded and displayed
window.document.getElementById("showButton").addEventListener("htmx:afterOnLoad", function() {
setTimeout(function(){
window.document.getElementById("modal").classList.add("uk-open")
}, 10)
})
// This triggers the fade-out animation when the modal is closed.
window.document.getElementById("cancelButton").addEventListener("click", function() {
window.document.getElementById("modal").classList.remove("uk-open")
setTimeout(function(){
window.document.getElementById("modals-here").innerHTML = ""
,200
})
})