需要在 "active" 导航 link 的页面加载时保持 CSS 转换

Need to keep a CSS transform on page load for "active" nav link

我有一个导航栏,它使用 CSS 变换在鼠标悬停时在 link 的顶部扩展一个栏。我还想要一个#active id,所以相应的 link 应用了结束样式。由于 CSS 转换语法的性质,我无法完成此操作。

http://codepen.io/anon/pen/doXMog

#active:before {
    position: absolute;
    top: 0;
    left: 0;
    margin-top:2px;
    width: 100%;
    height: 6px;
    background: red;
    content: '';
}

为了澄清起见,我希望更改文本颜色并在页面加载时显示栏,与 :hover 上应用的样式相同。当然,这种风格只有在鼠标悬停在上面并伴有动画时才会应用。

感谢您的浏览,希望有人有想法。

您只需要将transform: scaleX(1)!important应用到活跃的class。它必须很重要,否则将不起作用。

.active:before {
  transform: scaleX(1)!important;
}

如果您在单击菜单项时动态更改页面内容,您可以像这样使用 javascript 来切换活动 class。

var menu = document.querySelector('.nav');                     // Select '.nav' from document and store it in var menu 
document.onclick = function(e) {                               // when the document is clicked
  if (menu.contains(e.target)) {                               // if the menu contains the clicked element
    var active = menu.querySelector('.active');                // select the current active item from menu
    active.className = active.className.replace('active', ''); // remove the active class from the currently active item
    e.target.className += 'active';                            // add the active class to the clicked element
  }
}

(Codepen Example)

在上面的示例中,我冒昧地修复了您 html 中的列表标记。

ul 元素的唯一直接后代应该是 li 元素。

如果将锚点嵌套在列表项中,然后将应用于列表项的样式应用到锚点,则可以获得相同的外观和行为。