gpt4 book ai didi

css - 我应该使用 CSS :disabled pseudo-class or [disabled] attribute selector or is it a matter of opinion?

转载 作者:数据小太阳 更新时间:2023-10-29 09:10:05 25 4
gpt4 key购买 nike

我正在尝试设置禁用输入的样式。我可以使用:

.myInput[disabled] { }

.myInput:disabled { }

属性选择器是现代 CSS3 的方式和前进的方式吗?我曾经使用伪类,但我找不到任何关于它们是否是旧方法且不受支持或者它们是否相等并且您可以使用最喜欢的任何信息的信息。

我不需要支持旧的浏览器(它是一个内网应用程序),所以是:

  • 属性更新更好
  • 伪类仍然是可行的方法
  • 你最喜欢哪个
  • 有一个技术原因需要使用一个而不是另一个

最佳答案

Is the attribute selector the modern CSS3 way and the way to go forward?

  • attribute is newer and better

没有;实际上,属性选择器自 CSS2 以来就已经存在了。 ,并且 disabled 属性本身自 HTML 4 以来就已存在.据我所知,:disabled 伪类是在 Selectors 3 中引入的。 , 这使得伪类更新。

  • there's a technical reason to use one over the other

是的,在某种程度上。

使用属性选择器,您依赖于您正在设置样式的文档使用 disabled 属性来指示禁用字段的知识。理论上,如果您设计的不是 HTML 的样式,禁用的字段可能不会使用 disabled 属性来表示,例如它可能是 enabled="false" 或类似的东西。甚至 future 的 HTML 版本也可能引入新元素,这些元素使用不同的属性来表示启用/禁用状态;这些元素与 [disabled] 属性选择器不匹配。

:disabled 伪类将选择器与您正在使用的文档分离。该规范简单地声明它以禁用的元素为目标,并且元素是启用、禁用还是两者都不启用,是defined by the document language instead。 :

What constitutes an enabled state, a disabled state, and a user interface element is language-dependent. In a typical document most elements will be neither :enabled nor :disabled.

换句话说,当您使用伪类时,UA 会根据您正在设置样式的文档自动找出要匹配的元素,因此您不必告诉它如何匹配。相反,属性选择器将匹配任何具有 disabled 属性的元素,而不管该元素实际上是否支持启用或禁用,例如 div。如果您使用的是众多依赖此类非标准行为的现代框架之一,则使用属性选择器可能会更好。

就 DOM 而言,我认为在 DOM 元素上设置 disabled 属性也会修改 HTML 元素的 disabled 属性,这意味着选择器与DOM 操作。我不确定这是否取决于浏览器,但是 here's a fiddle在所有主要浏览器的最新版本中演示它:

// The following statement removes the disabled attribute from the first input
document.querySelector('input:first-child').disabled = false;

您很可能会设计 HTML 样式,因此这些对您来说可能没有任何不同,但如果浏览器兼容性不是问题,我会选择 :enabled :disabled 而不是 :not([disabled])[disabled] 只是因为伪类带有属性选择器没有的语义。我就是这样的纯粹主义者。

关于css - 我应该使用 CSS :disabled pseudo-class or [disabled] attribute selector or is it a matter of opinion?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20141450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com