css - 如何使链接仅在访问后更改颜色
问题描述
当我在代码中的原始样式之后应用 :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;
}
我的预期结果是链接的背景为深灰色,文本颜色为深红色。
实际结果是只有橙色文本颜色的链接,我只在访问链接后才想要它。
解决方案
您所显示的内容不起作用的一个原因是因为<!-- -->
不是有效的 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>
推荐阅读
- javascript - 日期最小值和最大值,onchange 事件侦听器迄今为止无法正常工作
- javascript - loadSVGFromString 没有将标签识别为对象
- javascript - 为什么 @change 或 @input 可以与自定义 v-model 组件一起使用?
- reactjs - 我需要访问对象消息中的数据:“{'data':{'status':'active'}}”。stringfy 访问时抛出错误
- python - STDIN 向命令行发送回复的问题
- javascript - 我如何根据财产对象的数量增加变量
- flutter - 如何在颤动中将标记从 API 动态放置到谷歌地图?
- c++ - 如何从 void click 函数中获取图像数据?
- php - 使用 updateOrCreate() 时出现重复条目
- python - Django 虚拟环境 - 没有名为“gunicorn”的模块