许多 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 的平滑动画。它延迟 10ms 以便 UIKit 的动画 能够正确运行。
最后,服务器响应一个稍作修改的 UIKit 标准模态版本
<div id="modal" class="uk-modal" style="display:block;">
<div class="uk-modal-dialog uk-modal-body">
<h2 class="uk-modal-title">模态对话框</h2>
<p>此模态对话框由 HTMX 动态加载。</p>
<form _="on submit take .uk-open from #modal">
<div class="uk-margin">
<input class="uk-input" placeholder="你的名字是什么?">
</div>
<button type="button" class="uk-button uk-button-primary">保存更改</button>
<button
id="cancelButton"
type="button"
class="uk-button uk-button-default"
_="on click take .uk-open from #modal wait 200ms then remove #modal">关闭</button>
</form>
</div>
</div>
按钮和表单上的 Hyperscript 在此对话框完成或取消时触发动画。如果您不使用此 Hyperscript,模态对话框仍然可以工作,但 UIKit 的 淡入动画将不会被触发。
当然,您可以使用 JavaScript 而非 Hyperscript 来完成此工作,只是代码会多得多:
// 此代码在模态对话框加载并显示时触发淡入动画
window.document.getElementById("showButton").addEventListener("htmx:afterOnLoad", function() {
setTimeout(function(){
window.document.getElementById("modal").classList.add("uk-open")
}, 10)
})
// 此代码在模态关闭时触发淡出动画。
window.document.getElementById("cancelButton").addEventListener("click", function() {
window.document.getElementById("modal").classList.remove("uk-open")
setTimeout(function(){
window.document.getElementById("modals-here").innerHTML = ""
,200
})
})