悬停链接以使用 css 更改 *PAGE* 背景颜色

2022-01-22 00:00:00 background hover css

是否可以在使用 css 将鼠标悬停在页面上单独 div 中的不同链接上时更改整个页面背景?我对JS不是很熟悉,所以如果JS是强制性的,就需要解释一下.感谢任何帮助.谢谢!

Is it possible to change the whole page background when hovering over different links in a seperate div on the page using css? I am not very experienced with JS, so explaining will be needed if JS is mandatory. Appreciate any help. Thank you!

推荐答案

嗯,这是有可能的.您实际上不会更改页面的背景,但效果会相似.

Well, it is somehow possible. You won't be actually changing the page's background, but the effect will be similar.

看看代码.

    body {
        background: lightblue;
    }
    a:hover:before {
        content: '';
        position: absolute;
        display: block;
        top: 0; bottom: 0; left: 0; right: 0;
        z-index: -1;
    }
    li:nth-of-type(1) a:hover:before {
        background-color: blue;
    }
    li:nth-of-type(2) a:hover:before {
        background-color: red;
    }
    li:nth-of-type(3) a:hover:before {
        background-color: green;
    }

基本上,当光标悬停在链接上时,您只需创建一个伪元素.该伪元素的上、下、左、右的绝对位置等于 0,将占据整个屏幕,并给它一个 z-index -1 将确保它低于页面上的所有其他元素.当然,您在相应的伪元素中声明背景颜色或图像.

Basically you just have to create a pseudoelements when a cursor hovers over a link. That pseudoelement, having absolute position with top, bottom, left and right equals 0, will take the whole screen and giving it a z-index -1 will make sure it will be below every other elements on a page. Of course you declare a background color or image in a corresponding pseudoelement.

不过,有一个缺点.它不太灵活.例如,如果任何祖先元素的位置不是静态(默认),这将有点难以实现——如果不是不可能的话——因为您必须调整顶部、底部、左侧和右侧属性.

There's a drawback, though. It's not too flexible. For example, if any of ancestor elements will have a position other than static (default), this will be a bit harder - if not impossible - to implement, since you will have to adjust the top, bottom, left, and right properties.

相关文章