input[checked] CSS 收音机输入的选择器在 IE7 中不匹配

input[checked] CSS selector on radio input is not matching in IE7

我正在尝试将样式应用于具有 CHECKED 属性的单选按钮的标签,但我尝试的所有内容都无法在 IE7 上匹配。

示例 (JSFiddle):

<!DOCTYPE html>
<html>
    <head>
        <title>Title</title>
        <style type="text/css">
            /* Ensure that + selectors work */
            input + span { color: blue; }

            /* Try [checked] alone */
            input[checked] + span { color: red; }

            /* Try selecting by value */
            input[checked="checked"] + span { color: green; }
        </style>
    </head>
    <body>
        <form>
            <input type="radio" checked="checked" name="x" /><span>One</span>
            <input type="radio" name="x" /><span>Two</span>
            <input type="radio" name="x" /><span>Three</span>
        </form>
    </body>
</html>

所有 SPAN 的文本都是蓝色的,但第一个在 IE7 中既不是红色也不是绿色(在 IE11 中是原生的和模拟的)。我是否需要 JS hack-arounds,或者是否有一些 CSS 的技巧可以用来实现它?

这很奇怪。 IE7 支持属性选择器(至少是基本的)。它必须是特定于 checked 属性的东西。如果您将选中的属性更改为任何其他属性名称(有效或无效),选择器将起作用。只需尝试删除 'ed' 使其成为 'check' 并且存在和相等选择器都有效。不确定这是否与 IE7 在解析文档时未设置 defaultChecked DOM(不是 HTML)属性有关。

Internet Explorer 8 and later. In IE8 mode, parsing operations on the checked content attribute always affect both the checked content attribute and defaultChecked DOM attribute. For example, removeAttribute('checked') sets both checked and defaultChecked to false. Similarly, setAttribute('checked', 'checked') sets both DOM attributes to true (as if the element was being re-parsed).

来自:https://msdn.microsoft.com/en-us/library/ie/ms533715(v=vs.85).aspx

如果您有大量需求(很多元素),您可以尝试 Selectivizr - 有条件地为 IE6-IE8 加载(Selectivizr 支持的内容):

<!--[if (gte IE 6)&(lte IE 8)]>
  <script type="text/javascript" src="libs/selectivizr.js"></script>
<![endif]-->

如果您只有一两个地方,您可以使用 jQuery(或普通的 JavaScript)事件处理程序。这不是我通常会写的方式,但我通常的方法在 IE7 中不起作用;这是 唯一 在 IE7 中工作的:

$('input[name="x"]').on('change', function(){
    $('input[name="x"]').siblings('span').removeClass('red');
    $(this).next('span').addClass('red');
});

CSS:

.red{
    color:red;
}