如何在 CSS 中将颜色设置为用户的链接颜色

How to set the color to the user's link color in CSS?

本文关键字:颜色 设置 链接 用户 CSS      更新时间:2023-09-26

我想让一个元素使用浏览器默认用于未访问链接的相同颜色。我该怎么做?

<div style="color:???">This should have the same color</div>
<a href=".">as this!</a>

此外,如果可能的话,它也应该在较旧的浏览器中工作。JavaScript是可能的。

你可以

这样做:

var colored = document.getElementsByClassName('colored')[0];
style = window.getComputedStyle( document.querySelector( '.links' ), ':link'),
color = style.getPropertyValue('color');
colored.style.color = color;
a:link{
  color: #FF5656;
}
<div class="colored" style="color:???">This should have the same color</div>
<a class="links" href="">as this!</a>

如果我理解正确,像currentColor这样的东西可以做到这一点,但在这种情况下你需要继承,所以我已经包装了diva

currentColor 关键字表示 元素的color属性。它允许使颜色属性 由属性或子元素属性继承,这些属性不是 默认继承它。

它还可用于继承 元素的 color 属性,等效于继承 关键字(如果有)。

片段

#parent {
  color: red
}
a:link,.child {
  color: currentColor
}
<div id="parent">
  <a href="#">This will be red</a>
  <div class="child">This will have the same color has the link</div>
</div>

两种简单的方法:

方法一:使用<a>标签。只需使用 <a> 标签,因为它用于超链接,但没有"href"。 <div>标记取决于您的程序。

<div><a>This should have the same color</a><div>
<a href="#">as this!</a>

方法2:使用css。

            .SameColor {
              color: #0000EE;
            }
<div class="SameColor">This should have the same</div>
<a href="#">as this!</a>