许多 CSS 工具包包含用于创建模态对话框的样式(以及 Javascript)。此示例展示了如何使用 HTMX 使用 UIKit 显示动态对话框,以及如何用很少或根本不用 Javascript 触发其动画样式。
我们从一个触发对话框的按钮开始,以及一个位于标记底部用于加载对话框的 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
})
})