【问题标题】:Changing body background when hovering over a link将鼠标悬停在链接上时更改正文背景
【发布时间】:2018-02-26 20:56:52
【问题描述】:

我想设置我的页面,以便当用户将鼠标悬停在 div 中的链接上时,主体背景的颜色会发生变化,但仅限于悬停时。这是css

body {
  background-color: black;
}

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

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

【问题讨论】:

  • 你会用javascript吗?据我所知,您所要求的仅靠 CSS 是不可能的
  • 我对javascript有基本的了解,我愿意接受任何想法。

标签: html css


【解决方案1】:

您想要做的实际上是 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>

【讨论】:

    【解决方案2】:

    简短的回答:在纯 CSS 中还不能这样做,但是......


    长答案: 有一个伪类:has() 可以选择具有特定属性的元素。在你的情况下,它会是这样的:body:has(div a:hover)

    不幸的是,它还有no support


    但是,使用 HTML <input><label> 元素是 possible 这样做,除非您不能更改 background-color<body> 元素,因为 <body> 开始标记是由浏览器在任何之前自动生成的应该在其中的元素no matter where in code it's actually written

    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%;
    }
    

    【讨论】:

      【解决方案3】:

      它不是很漂亮,但你可以在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/

      【讨论】:

        猜你喜欢
        • 2020-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多