簡體   English   中英

將鼠標懸停在鏈接上時更改正文背景

[英]Changing body background when hovering over a link

我想設置我的頁面,以便當用戶將鼠標懸停在 div 中的鏈接上時,主體背景的顏色會發生變化,但僅在懸停時發生。 這是css

body {
  background-color: black;
}

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

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

當您詢問是否有父選擇器時,您想要做的實際上是不可能的 CSS,但我們可以使用一些解決方法。

這里有一個想法,我使用偽元素從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>

簡短回答:目前還不可能在純 CSS 中這樣做,但是......


長答案:有一個偽類:has()可以選擇具有特定屬性的元素。 在你的情況下,它會是這樣的: body:has(div a:hover)

不幸的是,它還沒有支持


但是,可以使用 HTML <input><label>元素來做到這一點,除非您不能更改<body>元素的background-color ,因為<body>開始標記是由瀏覽器在任何應該在內部的元素之前自動生成的無論它實際寫在代碼中的哪個位置

HTML:

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

CSS:

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

它不是很漂亮,但是您可以在body上使用:before偽元素

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

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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM