如何在悬停另一个 link 时更改 link 的颜色?

How to change the color of a link on hover of an another link?

这是一个代码

 <a id="link1" href="#" >About</a>
 <a id="link2" href="#">Contact us</a>

我希望在悬停 link2 时更改 link1 的颜色。 css 可以吗?

由于CSS似乎无法处理这个问题,请尝试JavaScript

window.onload=function() {
  document.getElementById("link2").onmouseover=function() {
    document.getElementById("link1").style.color="red";
  }
  document.getElementById("link2").onmouseout=function() {
    document.getElementById("link1").style.color="blue";
  }
}
 <a id="link1" href="#" >About</a>
 <a id="link2" href="#">Contact us</a>

或使用兄弟姐妹

function prevSib(elem) {do { elem = elem.previousSibling;} while ( elem && elem.nodeType !== 1 ); return elem; }

window.onload=function() {
  document.getElementById("link2").onmouseover=function() {
    prevSib(this).style.color="red";
  }
  document.getElementById("link2").onmouseout=function() {
    prevSib(this).style.color="blue";
  }
}
<a id="link1" href="#" >About</a>
<a id="link2" href="#">Contact us</a>

使用纯 css 不可能倒退。您可以采用级联方式。

但是,您可以使用 JQuery 来完成。喜欢:

$(document).ready(function(){
    $(".link2").mouseover(function(){
        $(".link1").css("color", "red");
    });
     $(".link2").mouseout(function(){
        $(".link1").css("color", "black");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="link1" class="link1" href="#" >About</a>
 <a id="link2" class="link2" href="#">Contact us</a>

希望对您有所帮助。

CSS不能select以前的兄妹。您可以使用 JavaScript:

var links = [].slice.call(document.querySelectorAll('.menu_item'));

function hover(event) {
   var pre = this.previousElementSibling,
       method = event.type === 'mouseenter' ? 'add' : 'remove'; 

   if (pre) {
       pre.classList[method]('active'); 
   }
}

links.forEach(function(el) {
    el.addEventListener('mouseenter', hover);
    el.addEventListener('mouseleave', hover);
});

以上代码假定 a 元素具有 menu_item 的 class 和 active 的 class 应该添加到前一个兄弟悬停元素。

Here is a demo.

使用 JavaScript 来做到这一点(link1 的颜色在悬停 link2 时改变)。您需要使用 html 标签属性,例如 onmouseoveronmouseout.

试试这个代码。悬停 link2 时更改 link1 的颜色。

<html> 
<head>


<script>

function colorchange(){
 document.getElementById("link1").style.color="red";
}
function colorchange2(){
 document.getElementById("link1").style.color="blue";
}
</script>
</head>
<body>

<a id="link1" href="#" >About</a>
 <a id="link2" onmouseover="colorchange()" onmouseout="colorchange2()" href="#">Contact us</a>

</body>
</html>

我想这就是您要找的。
首先,您需要将链接包装在这样的容器中

<div class='container'>
    <a id="link1" href="#" >About</a>
    <a id="link2" href="#">Contact us</a>
</div>

然后应用此样式

.container:hover a:not(:hover){
    color:red;
}

css only demo here
更新
正如我在下面的 5 月评论中所说,我假设您想更改所有未悬停链接的样式,但是如果您只想在悬停 link2 时更改 link1,但在悬停 link1 时不更改 link2 的样式,您可以写 css像这样
second demo

.container:hover a:first-child:not(:hover){
    color:red;
}