【问题标题】:Chrome and CSS attribute selectorChrome 和 CSS 属性选择器
【发布时间】:2013-06-10 00:53:26
【问题描述】:

我有以下 HTML 代码,我想用 css 格式化一个无法更改的数据格式(来自 xml)。

我必须为具有不同属性值的元素赋予不同的样式。我想使用 CSS 属性选择器。

body {
    background-color: black
}
s {
    text-decoration: none
}
f {
    color: black;
    text-decoration: none;
    display: block;
}
f[type=h2] {
    color: green
}
f[type=p] {
    color: blue
}
f[type=speech] {
    color: yellow
}
f[type=other] {
    color: gray
}
<b>
  <s> 
    <f type="h2">Title</f>
    <f type="p">Paragraph</f>
    <f type="speech">Dialgoue</f>
    <f type="other" br="true">Other</f>
    <f type="p">Paragraph</f>
    <f type="p">Paragraph</f>
  </s>
</b>

在 Firefox 中,页面按照我的预期呈现(h2 为绿色,p 为蓝色,speech 为黄色,其他为灰色)。在 chrome 中,一切都是绿色的。

如何在 Chrome 中获取 Firefox 结果?

【问题讨论】:

  • 您使用的是文档类型吗?
  • 很少有人意识到您可以使用 CSS 或 XSLT 设置 XML 样式。
  • @Zenith OP 正在尝试设置 XML 文档而不是常规 HTML 的样式...
  • @MarcAudet 哎呀,这表明我可以直接进入代码!

标签: html css google-chrome css-selectors


【解决方案1】:

您的 HTML 无效。如果您通过验证器运行它,它会吐出错误,因为它不喜欢命名的嵌入式 XML 标记。

根据HTML/XML Task Force Report

当 HTML5 解析器遇到不熟悉的标记时,它会假定此类标记是生成定义明确的 HTML5 的错误尝试。因此,它应用了纠错策略,导致 DOM 表示可能与 XML 解析器生成的 DOM 完全不同。特别是,打开的元素可能会提前结束,并且可能会打开其他元素。

实际结果是,HTML5 文档中的“裸”XML 岛无法可靠地生成任何类似于人们通过随意检查 XML 岛所期望的 DOM。

因此,Chrome 完全有权在这里搞砸,因为从技术上讲,您首先做到了。值得注意的是(在我的 Chrome 浏览器中)all the elements are green (http://jsfiddle.net/qJMWg/) - 这表明出于某种原因,它们都嵌套在一个大的 &lt;f type="h2"&gt; 元素中。这是值得注意的,因为 HTML 确实包含 &lt;b&gt;&lt;s&gt; 标记,所以 &lt;f&gt; 是它遇到的第一个无效标记。

If we change the styles for that f\[type=h2\] rule (http://jsfiddle.net/qJMWg/1/) 它会影响一切——这与 Chrome 以某种方式错误地解释此 XML 结构的想法一致。对于 Chrome 的 CSS 引擎(尽管开发人员工具告诉我们),这看起来像这样:

    <b>
      <s> 
        <f type="h2">Title&lt;/f&gt;
        &lt;f type="p"&gt;Paragraph&lt;/f&gt;
        &lt;f type="speech"&gt;Dialgoue&lt;/f&gt;
        &lt;f type="other" br="true"&gt;Other&lt;/f&gt;
        &lt;f type="p"&gt;Paragraph&lt;/f&gt;
        &lt;f type="p"&gt;Paragraph</f>
      </s>
    </b>

【讨论】:

  • 实际上我对生成的 DOM 结构的解释可能不太正确 (http://jsfiddle.net/qJMWg/2/),但核心信息是一样的:这是无效的 HTML,Chrome 可以用它做任何事情。跨度>
【解决方案2】:

更改 attr 名称会对您有所帮助,我不知道为什么

        <f custom="p">Paragraph</f>
        <f custom="speech">Dialgoue</f>
        <f custom="other" br="true">Other</f>
        <f custom="p">Paragraph</f>
        <f custom="p">Paragraph</f>


   <style type="text/css">
        f[custom=h2] {
            color: green;
        }
        f[custom=p] {
            color: blue;
        }
        f[custom=speech] {
            color: yellow;
        }
        f[custom=other] {
            color: gray;
        }
    </style>

【讨论】:

  • 这是一种魔法!不幸的是,我不可能更改属性名称。
  • 你可以使用 jQuery 通过 .css() 为这些元素提供 css
【解决方案3】:

由于某些未知原因,Chrome 对 HTML 标记相当严格,因此 CSS 规则在上述浏览器中无法正常工作。

一个建议,你为什么不style the XML 代替?

【讨论】:

  • 其他人建议使用此解决方案。这是最简单最清楚的。谢谢。
猜你喜欢
  • 2016-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-19
  • 2018-06-05
  • 2011-10-17
相关资源
最近更新 更多