hx-indicator
hx-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>
当请求正在进行时,这将导致 htmx-request
类被添加到 #spinner
图像中。图像上也有 htmx-indicator
类,它定义了一个不透明度过渡,将显示加载图标
.htmx-indicator{
opacity:0;
transition: opacity 500ms ease-in;
}
.htmx-request .htmx-indicator{
opacity:1;
}
.htmx-request.htmx-indicator{
opacity:1;
}
如果您更喜欢使用不同的效果来显示加载图标,您可以定义和使用自己的指示器 CSS。以下示例使用 display
而不是不透明度(注意我们使用 my-indicator
而不是 htmx-indicator
)
.my-indicator{
display:none;
}
.htmx-request .my-indicator{
display:inline;
}
.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
。参见 配置 htmx。最简单的方法是在 HTML 的 <head>
中添加以下内容<meta name="htmx-config" content='{"includeIndicatorStyles": false}'>