更改<a> hover

时间:2015-07-14 19:33:27

标签: html css

I have a landing page with a welcome title. On hover I would like not only the <a> text to change cover but the background of <header> to change background color.

I understand you can't alter the parent tag on hover of a child element. I did try using a sibling div but this didn't work either.

<header>
  <div>
    <h1>This is a <a href="#">link</a> to go somewhere.</h1>
  </div>
  <div id="headerhover"></div>
</header>

2 个答案:

答案 0 :(得分:1)

你只需要hover使用a

请参阅下面的代码:

h1 a {
  color: black
}
h1 a:hover {
  color: green;
  background-color: red
}
<header>
  <div>
    <h1>This is a <a href="#">link</a> to go somewhere.</h1>
  </div>
</header>

经过仔细阅读,我明白你希望父母改变背景,纯CSS无法做到。因为CSS只支持级联方向的样式,而不是支持。

但是,在这种情况下,如果我们使用pointer-events,则可以查看:

header {
  pointer-events: none;
}
header:hover {
  background: yellow
}
header h1 a {
  color: black;
  pointer-events: auto;
}
header h1 a:hover {
  color: green;
}
<header>
  <div>
    <h1>This is a <a href="#">link</a> to go somewhere.</h1>
  </div>
</header>

答案 1 :(得分:0)

jQuery解决方案,将是

&#13;
&#13;
$('a').hover(
  function() {
    $(this).closest('header').css({'background':'red'});
  }, 
  function() {
    $(this).closest('header').css({'background':'yellow'});
  }
);
&#13;
header {width:100%; height:1000px; background:cyan;}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<header>
	<div><h1>This is a <a href="#">link</a> to go somewhere.</h1></div>
        <div id="headerhover"></div>
</header>
&#13;
&#13;
&#13;