4

理解HTML 5.1的新增inert 属性

 1 year ago
source link: https://www.fly63.com/article/detial/12200
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

inert属性介绍

inert是 htmlElement 的一个布尔属性,意为"惰性",简单来说,可以禁用一切交互,包括鼠标点击、选中、拖拽、键盘操作等等。

简单理解,一个dom元素被加了 inert 属性后,就丧失了活力,变得不可交互,就好像整个 DOM 都被冻结了一样,所以理解成“冻结”。如果一个元素被inert了,那它的内容就不能被 Ctrl+F 搜索到,window.find(text)也需要跳过

另外,inert是一个布尔类型的属性,就是和平时见到的disabled、hidden等一致,只要有这个属性,就表示为true,不存在才是false。

[inert] {
  pointer-events: none;
  cursor: default;
}

[inert], [inert] * {
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

语法

isInert = HTMLElement.inert;
HTMLElement.inert = true | false;

一个布尔值,如果元素是惰性的,则为 true ;否则,该值为 false 。

html:

<div>
  <label for="button1">Button 1</label>
  <button id="button1">I am not inert</button>
</div>
<div inert>
  <label for="button2">Button 2</label>
  <button id="button2">I am inert</button>
</div>

css

[inert] > * {
  opacity: .5;
}

注意:该属性本身不会对浏览器中显示的内容造成任何视觉变化。在上面的示例中,已应用 CSS,因此具有 inert 属性的元素的任何直接后代都呈现为半透明。

那有什么场景可以用到呢?举一个例子:

假设在一个左右切换卡片的场景,左右的卡片还没有被滑动到中间,但是又露出了一点内容,刚好这露出的部分有一个按钮,通常情况下,在没有滑动到中间的时候,这部分内容应该是不允许产生点击交互的。那就可以通过给非active的卡片添加 inert 。

当然对于上面提到的有视力障碍的人,他不是依靠视觉来感知网页内容,而是借助了一些其他的辅助技术,这就有可能会和我们隐藏掉的内容进行一些意外的交互。

inert属性兼容性

inert 在 Chrome 102 中提供支持,并且在 Firefox 和 Safari 中也都是可用的。

这类比较偏体验的属性其实是不太需要关注兼容的,大部分地方其实都用不上,如果你悄悄在某个地方用了也无妨,浏览器能支持更好,不支持也不影响主要功能。下面是兼容性情况:

63477c14269fc.jpg

总之即使非常新,也可以提前使用起来了,下面总结一下主要知识点:

  1. inert是一个 HTMLElement 属性,可以禁用一切用户交互,非常彻底,就像“冻结”了一样
  2. inert是一个布尔属性,只要存在该属性就是true,否则为false
  3. inert可以很方便的禁用a链接,也包括其他任意元素
  4. inert可以很方便的控制焦点的作用范围,让弹窗内的焦点不会跳到外部
  5. 原生dialog.showModal已经天然具备局部焦点的特性,大家可以多多使用

链接: https://www.fly63.com/article/detial/12200


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK