gpt4 book ai didi

css - 更改选择器属性 CSS

转载 作者:行者123 更新时间:2023-11-28 09:47:12 26 4
gpt4 key购买 nike

是否可以在 CSS 中将选择器属性更改为另一个选择器属性?

例如,使用 .button:focus 我想更改主体的背景,如下所示:

body {
background-image: url(../images/banana.jpg);
transition: background-image 2s;
}

.button:focus, body {
background-image: url(../images/apple.jpg)<-- but I just want to change the background of the body, not from the button also
transition: background-image 2s;
}

最佳答案

没有。

(抱歉)

CSS 无法提升 DOM,这不是它的工作方式 - 因此任何作为 body 子元素的元素,例如按钮,都无法遍历 并设置样式>body 使用 CSS 选择器。

因此有两种方法可以做到这一点:

  1. 使用 javascript 添加/更改按钮点击时 body 的样式

  2. 有一个绝对定位,宽度/高度 100% top left:0 div 覆盖在 body 上,然后做,例如:

Demo Fiddle

HTML

<button>Click me!</button>
<div></div>

CSS

html, body, div {
height:100%;
width:100%;
margin:0;
padding:0;
position:relative;
}
body {
background:grey;
}
div {
display:none;
background:red;
position:absolute;
left:0;
top:0;
}
button {
z-index:1;
position:relative;
}
button:focus + div {
display:block;
z-index:0;
}

但是,由于实现这项工作所需的各种依赖项,这可能无法在生产环境中工作,因此第一种解决方案更可取。

关于css - 更改选择器属性 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25205490/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com