简体   繁体   English

将鼠标悬停在链接上时更改正文背景

[英]Changing body background when hovering over a link

I would like to set up my page so that when the user hovers over a link in a div, the color of the body background is changed, but only while hovering.我想设置我的页面,以便当用户将鼠标悬停在 div 中的链接上时,主体背景的颜色会发生变化,但仅在悬停时发生。 This is the css这是css

body {
  background-color: black;
}

a {
  color: white;
  text-decoration: none;
}

a:hover {
  color: white;
  background-color: transparent;
  text-decoration: underline;
}

What you want to do is actually not possible with CSS as you are asking if there is a parent selector BUT we can use some workarounds.当您询问是否有父选择器时,您想要做的实际上是不可能的 CSS,但我们可以使用一些解决方法。

Here is an idea where I use a pseudo element from the a that I make it to cover the whole body and it behaves as the background of the body:这里有一个想法,我使用伪元素从a我使其覆盖全身,它表现为身体的背景:

 a { color: white; text-decoration: none; } a:before { content: ""; position: fixed; top: 0; right: 0; left: 0; bottom: 0; background: #000; z-index: -1; pointer-events:none; } a:hover::before { background: red; }
 <a href="#">link</a>

Short answer: It's not possible to do so in pure CSS yet, however...简短回答:目前还不可能在纯 CSS 中这样做,但是......


Long answer: There's a pseudoclass :has() that can select element, that has specific properties.长答案:有一个伪类:has()可以选择具有特定属性的元素。 In your case it would be something like this: body:has(div a:hover) .在你的情况下,它会是这样的: body:has(div a:hover)

Unfortunatelly, it has no support yet.不幸的是,它还没有支持


However it's possible to do so using HTML <input> and <label> elements except you can't change background-color of <body> element, because <body> start tag is generated automatically by the browser before any element that should be inside it no matter where in code it's actually written .但是,可以使用 HTML <input><label>元素来做到这一点,除非您不能更改<body>元素的background-color ,因为<body>开始标记是由浏览器在任何应该在内部的元素之前自动生成的无论它实际写在代码中的哪个位置

HTML: HTML:

<body>
    <input id="magic" type="checkbox">
    <div>
        <label for="magic"><a href="#">Link</a></label>
    </div>
</body>

CSS: CSS:

html, body, div {
    margin: 0;
    height: 100%;
}
#magic:hover + div {
    background: red;
}
input {
    position: fixed;
    left: -100%;
}

It's not very pretty, but you can use the :before pseudo-element on body它不是很漂亮,但是您可以在body上使用:before伪元素

<a class="change-bg" href="">link 1</a>

CSS: CSS:

body {
    background: #fff;
}

a.change-bg:hover:before {
    content:'';
    position: absolute;
    display: block;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: -1;
    background-color: #000;
}

http://jsfiddle.net/bjsvhze8/13/ http://jsfiddle.net/bjsvhze8/13/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM