hx-preservehx-preserve 属性允许你在 HTML 替换期间保持元素不变。当 htmx 更新任何祖级元素时,设置了 hx-preserve 的元素将由 id 保留。你必须在元素上设置一个不变的 id 才能使 hx-preserve 正常工作。响应需要具有相同 id 的元素,但其类型和其他属性将被忽略。
¥The hx-preserve attribute allows you to keep an element unchanged during HTML replacement.
Elements with hx-preserve set are preserved by id when htmx updates any ancestor element.
You must set an unchanging id on elements for hx-preserve to work.
The response requires an element with the same id, but its type and other attributes are ignored.
¥Notes
hx-preserve 不是继承的
¥hx-preserve is not inherited
你可以使用 hx-preserve="true" 或将其用作仅 hx-preserve 的布尔属性
¥You can use hx-preserve="true" or use it as a boolean attribute with just hx-preserve
不幸的是,有些元素无法正确保存,例如 <input type="text">(焦点和插入符号位置丢失)、iframe 或某些类型的视频。为了解决其中一些情况,我们推荐使用 morphdom 扩展,它可以进行更复杂的 DOM 协调
¥Some elements cannot unfortunately be preserved properly, such as <input type="text"> (focus and caret position are lost), iframes or certain types of videos. To tackle some of these cases we recommend the morphdom extension, which does a more elaborate DOM
reconciliation
当使用 历史记录支持 执行后退按钮等操作时,hx-preserve 元素的状态也会保留
¥When using History Support for actions like the back button hx-preserve elements will also have their state preserved
避免在可能包含 hx-preserve 元素的请求中使用设置为 none 的 hx-swap,以免丢失它
¥Avoid using hx-swap set to none with requests that could contain a hx-preserve element to avoid losing it
hx-preserve 可导致元素从其当前位置移除并在部分/oob 响应中进行交换时重新定位到新位置
¥hx-preserve can cause elements to be removed from their current location and relocated to a new location when swapping in a partial/oob response
<div id="new_location">
Just relocated the video here
<div id="video" hx-preserve></div>
</div>
可用于 hx-swap-oob 元素的内部内容
¥Can be used on the inside content of a hx-swap-oob element
<div id="notify" hx-swap-oob="true">
Notification updated but keep the same retain
<div id="retain" hx-preserve></div>
</div>