此示例展示如何实现一个平滑滚动进度条。
我们从一个初始状态开始,其中包含一个按钮,该按钮向 /start
发出 POST
请求以开始工作
<div hx-target="this" hx-swap="outerHTML">
<h3>Start Progress</h3>
<button class="btn primary" hx-post="/start">
Start Job
</button>
</div>
然后,此 div 被替换为一个新的 div,其中包含状态和一个每 600 毫秒重新加载自己的进度条
<div hx-trigger="done" hx-get="/job" hx-swap="outerHTML" hx-target="this">
<h3 role="status" id="pblabel" tabindex="-1" autofocus>Running</h3>
<div
hx-get="/job/progress"
hx-trigger="every 600ms"
hx-target="this"
hx-swap="innerHTML">
<div class="progress" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" aria-labelledby="pblabel">
<div id="pb" class="progress-bar" style="width:0%">
</div>
</div>
</div>
此进度条每 600 毫秒更新一次,其“宽度”样式属性和 aria-valuenow
属性设置为当前进度值。由于进度条 div 上有一个 id,htmx 会通过将样式属性平滑地过渡到其新值来平滑地过渡请求。这与 CSS 过渡相结合,使视觉过渡变得连续,而不是跳跃。
最后,当进程完成时,服务器返回 HX-Trigger: done
头部,这将触发 UI 更新为“完成”状态,并向 UI 添加一个重启按钮(我们正在使用 class-tools
扩展在这个例子中为按钮添加淡入效果)。
<div hx-trigger="done" hx-get="/job" hx-swap="outerHTML" hx-target="this">
<h3 role="status" id="pblabel" tabindex="-1" autofocus>Complete</h3>
<div
hx-get="/job/progress"
hx-trigger="none"
hx-target="this"
hx-swap="innerHTML">
<div class="progress" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="122" aria-labelledby="pblabel">
<div id="pb" class="progress-bar" style="width:122%">
</div>
</div>
</div>
<button id="restart-btn" class="btn primary" hx-post="/start" classes="add show:600ms">
Restart Job
</button>
</div>
此示例使用从 bootstrap 进度条中借用的样式
.progress {
height: 20px;
margin-bottom: 20px;
overflow: hidden;
background-color: #f5f5f5;
border-radius: 4px;
box-shadow: inset 0 1px 2px rgba(0,0,0,.1);
}
.progress-bar {
float: left;
width: 0%;
height: 100%;
font-size: 12px;
line-height: 20px;
color: #fff;
text-align: center;
background-color: #337ab7;
-webkit-box-shadow: inset 0 -1px 0 rgba(0,0,0,.15);
box-shadow: inset 0 -1px 0 rgba(0,0,0,.15);
-webkit-transition: width .6s ease;
-o-transition: width .6s ease;
transition: width .6s ease;
}