首页 > 解决方案 > 如何使链接仅在访问后更改颜色

问题描述

当我在代码中的原始样式之后应用 :visited 样式时,:visited 样式会覆盖默认样式,这不会产生链接已被访问的效果。

我想要的默认样式是 .btn

访问链接后我想要的样式是 .btn:visited

我尝试将 :visited 样式移动到 :hover 样式的上方和下方。根据我的阅读,:visited 样式应该高于 :hover 样式。但它会覆盖我想以现在的方式应用于链接的默认样式。

<!-- I want this styling to be the default -->
.btn {
  margin-left: 10px;
  margin-right: 10px;
  background-color: darkgrey;
  color: darkred;
}

<!-- I want this styling to be applied only once visted -->
.btn:visited {
  color: orange;
}


.btn:hover {
  /* Applies to links under the pointer */
  font-weight: bold;
  background-color: darkgrey;
  color: darkred;
}

我的预期结果是链接的背景为深灰色,文本颜色为深红色。

实际结果是只有橙色文本颜色的链接,我只在访问链接后才想要它。

标签: csstwitter-bootstrapoverridingvisited

解决方案


您所显示的内容不起作用的一个原因是因为<!-- -->不是有效的 CSS 注释并且完全违反了下一条规则(因为

<!-- ... -->
some-selector

...不匹配some-selector)。

/* ... */但是,它是一个有效的 CSS 注释:

@import url(https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css);

/* I want this styling to be the default */
.btn {
  margin-left: 10px;
  margin-right: 10px;
  background-color: darkgrey;
  color: darkred;
}

/* I want this styling to be applied only once visted */
.btn:visited {
  color: orange;
}


.btn:hover {
  font-weight: bold;
  background-color: darkgrey;
  color: darkred;
}
<a class="btn" href="#test">test</a>

注意:请勿:visited在隐身模式下测试!因为在这种模式下,历史中没有任何内容被保存,因此没有任何内容可以是:visited.
要正确测试这一点,请确保您没有处于隐身模式并清除缓存(浏览历史记录)。


如果您的问题是浏览器确实记住了您:visited的链接,那么它应该是这样工作的。
如果页面中的锚点在href浏览器的历史记录中存在,并且:visited状态已设置样式(具有高于当前应用样式的特殊性),:visited则将应用该样式。这是预期的行为。如果您想更改它的工作方式(不推荐),请不要使用:visited不同的样式并在用户交互上应用自定义类。

例子:

$('.btn').on('click', function(){
  $(this).addClass('visited');
})
@import url(https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css);

/* I want this styling to be the default */
.btn {
  margin-left: 10px;
  margin-right: 10px;
  background-color: darkgrey;
  color: darkred;
}

/* I want this styling to be applied only once visted */
.visited {
  color: orange;
}


.btn:hover {
  font-weight: bold;
  background-color: darkgrey;
  color: darkred;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<a class="btn" href="#test">test</a>


推荐阅读