【问题标题】:How to get to last child如何得到最后一个孩子
【发布时间】:2013-04-19 22:34:19
【问题描述】:

我有 3 个 <a> 标记,我想将它们传递给 IE8 中的最后一个孩子。不幸的是 IE8 不支持:last-child

#breadcrumbs li:first-child div a {
  background: none !important;
  color: red !important;
}

顶部 css 到达第一个 <a> 但我需要尝试到达第三个,我尝试使用下面的代码但它不起作用。

#breadcrumbs li:first-child div a + li div a + li div a {
  background: none !important;
  color: red !important;
}


<ul id="breadcrumbs">
   <li><div><a>dfgdfg</a></div></li>
   <li><div><a>fdgdfgdf</a></div></li>
   <li><div><a>fdgdfgfd</a></div></li>
   <li><div><a>dgfdgdfg</a></div></li>
</ul>

【问题讨论】:

  • 你的 HTML 是什么?顺便说一句,li永远成为 a 元素的直接兄弟(无论您的 HTML 写得多么糟糕)。
  • 您必须包含您的 HTML。如果没有标记,就没有写 CSS 的意义
  • 所以在 #breadcrumbs 中总会有 4 个 li ?

标签: html css internet-explorer-8 css-selectors


【解决方案1】:

我有点猜测,但我建议:

#breadcrumbs li + li + li + li div a {
    /* css here */
}

JS Fiddle demo.

当然,您可以简单地将类名应用于lia 元素,然后根据该类名设置元素的样式。如果 JavaScript 可用,那么您当然可以在必要时使用 JavaScript 添加类:

var list = document.getElementById('breadcrumbs'),
    aElems = list.getElementsByTagName('a'),
    lastA = aElems[aElems.length - 1];
lastA.className = 'last';

JS Fiddle demo.

【讨论】:

  • 不是动态答案,是不是 IE8 的 last-child css hack ?
  • @S.Visser:不使用纯 CSS。
【解决方案2】:

ie9.js 将使 IE8 及以下版本达到最新规范。包括这应该允许使用伪选择器,如:last-child

只需将其包含在您的页面上,例如:

<!--[if lt IE 9]>
<script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE9.js"></script>
<![endif]-->

【讨论】:

    【解决方案3】:

    这是一个与 jQuery 结合使用的好方法。

       /* Load this in your DOM */
       function last_child() {
          if ($.browser.msie && parseInt($.browser.version, 10) <= 8) {
            $('*:last-child').addClass('last-child');
          }
        }
    

    只要穿上你的风格

    li:last_child, li.last_child {
    
    }
    

    示例:http://jsfiddle.net/2dcsH/

    【讨论】:

    • IE8 仍然会因为选择器中的 :last-child 而忽略 CSS 规则,所以这是徒劳的。您也可以为所有浏览器添加类,然后在 CSS 中选择该类。
    猜你喜欢
    • 2018-02-12
    • 2013-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 2013-03-12
    • 2012-02-09
    相关资源
    最近更新 更多