hx-indicatorhx-indicator 属性允许您指定在请求持续时间内将添加 htmx-request 类的元素。这可用于在请求进行时显示加载指示器或进度指示器。
此属性的值是一个 CSS 查询选择器,用于指定要应用该类的元素或元素组,或者是关键字 closest,后跟 CSS 选择器,它将找到匹配给定 CSS 选择器的最近祖先元素或自身(例如 closest tr)。
以下是一个与按钮相邻的加载指示器的示例:
<div>
<button hx-post="/example" hx-indicator="#spinner">
Post It!
</button>
<img id="spinner" class="htmx-indicator" src="/img/bars.svg"/>
</div>
请注意,您还可以使用 inherit 关键字来继承父元素的指示器值,并添加额外的指示器 CSS 选择器:
<main hx-indicator="#global-indicator">
...
<button hx-post="/example" hx-indicator="inherit, #spinner">
Post It!
</button>
<img id="spinner" class="htmx-indicator" src="/img/bars.svg"/>
</main>
当请求进行时,这将导致 htmx-request 类被添加到 #spinner 图像上。该图像还带有 htmx-indicator 类,该类定义了一个不透明度过渡效果,以显示加载指示器:
.htmx-indicator {
opacity: 0;
visibility: hidden;
}
.htmx-request .htmx-indicator,
.htmx-request.htmx-indicator {
opacity: 1;
visibility: visible;
transition: opacity 200ms ease-in;
}
此默认的 htmx-indicator CSS 还将可见性设置为隐藏,以提高屏幕阅读器的可访问性,并快速淡入不透明度。
如果您希望为显示加载指示器使用不同的效果,您可以定义并使用自己的指示器 CSS。以下是一个使用 display 而非不透明度的示例(注意,我们使用 my-indicator 而非 htmx-indicator):
.my-indicator{
display:none;
}
.htmx-request .my-indicator,
.htmx-request.my-indicator{
display:inline;
}
请注意,hx-indicator 选择器的目标不必是您想要显示的确切元素:它可以是指示器父层次结构中的任何元素。
最后,请注意,默认情况下 htmx-request 类会添加到引发请求的元素上,因此您可以将指示器放置在该元素内部,而无需使用 hx-indicator 属性明确指定它:
<button hx-post="/example">
Post It!
<img class="htmx-indicator" src="/img/bars.svg"/>
</button>
这模拟了在该情况下加载指示器可能的外观:
hx-indicator 是可继承的,可以放置在父元素上htmx-request 类将添加到触发请求的元素上htmx-indicator 作为类名,则需要禁用 includeIndicatorStyles。请参阅 Configuring htmx。最简单的方法是将此添加到 HTML 的 <head> 中:<meta name="htmx-config" content='{"includeIndicatorStyles": false}'>
htmx-indicator CSS 使用内联样式标签,如果您有严格的基于 nonce 的 CSP 策略用于 style-src,则可能需要设置 inlineStyleNonce 配置<meta name="htmx-config" content='{"inlineStyleNonce": "random-nonce"}'>
includeIndicatorStyles 并托管您自己的 CSS 文件,其中包含上述首选 htmx-indicator 样式的副本