4

我只需要使用仅使用 CSS 的类默认值为最后一个 li 着色。编辑 HTML 不是一种选择。IE9+ 没问题。如何只为最后一个链接着色?这只是一个示例,菜单是动态的,因此不能使用最后一个子项或指定确切的最后一个链接。我有一个这样的导航菜单:

<ul>
    <li class="default">
        <a href="#">About Us</a>
        <ul>
            <li class="default">
                <a href="#">Where we live</a>
                <ul>
                    <li class="default">
                        <a href="#">Make this link red only</a>
                    </li>
                    <li>
                        <a href="#">Directions</a>
                    </li>
                </ul>
            </li>
        </ul>
     </li>
 </ul>
4

2 回答 2

4

至于纯 CSS 方法,IE9 支持这些伪选择器。这也可以在 jquery 之类的东西中使用。但是,此代码的问题是,如果您有多个默认值,那么它将为它们着色。

li.default > a:only-child {
  color:red;            
}​
于 2012-11-27T23:21:37.990 回答
-1

我认为这个 PHP 解决方案最适合您的情况(这是我制作的 PHPfiddle 演示:点击“运行”并等待几秒钟)。

要实现这一点,请将其添加到 HTML 文件的顶部:

<?php $thisPage='Make this link red only'; ?>
<html><head>

然后将此 PHP(在<?phpand?>标记内)添加到所有导航项中:

     <ul>
        <li <?php if ($thisPage=='About Us') echo ' id="currentpage"'; ?>>
            <a href="#">About Us</a>
            <ul>
                <li<?php if ($thisPage=='Where we live') 
          echo ' id="currentpage"'; ?>>
                    <a href="#">Where we live</a>
                    <ul>
                        <li<?php if ($thisPage=='Make this link red only') 
          echo ' id="currentpage"'; ?>>
                            <a href="#">Make this link red only</a>
                        </li>
                        <li <?php if ($thisPage=='Directions') 
          echo ' id="currentpage"'; ?>>
                            <a href="#">Directions</a>
                        </li>
                    </ul>
                </li>
            </ul>
         </li>
     </ul>

然后将您的 CSS 设置为:

#currentpage a { color: red; }

您还必须重命名您的index.htmlas index.php,或者更好的解决方案是使用 .htaccess (假设您正在运行 Apache 服务器)来解析 HTML文件中的 PHP。

于 2012-11-27T23:31:47.197 回答