正如这里所描述的..。
..。CSS3支持逗号分隔的列表语法,用于在单个元素上分层多个背景。他们的示例css是这样的:
background-image: url(https://mdn.mozillademos.org/files/11305/firefox.png),
url(https://mdn.mozillademos.org/files/11307/bubbles.png),
linear-gradient(to right, rgba(30, 75, 115, 1), rgba(255, 255, 255, 0));
background-repeat: no-repeat,
no-repeat,
no-repeat;
background-position: bottom right,
left,
right;
假设我稍后只想修改其中一个层,比如通过JS或使用:hover
伪类。我如何能够只针对这些层中的一层。
例如,假设我想要将firefox徽标从bottom right
移动到top right
,并且想要将bubbles.png
层更改为重复的。
我如何通过CSS来实现这一点?
那么JS呢?
发布于 2018-06-26 07:07:23
简单的方法是重新定义这3个值:
.box {
width:200px;
height:200px;
background-image: url(https://mdn.mozillademos.org/files/11305/firefox.png),
url(https://mdn.mozillademos.org/files/11307/bubbles.png),
linear-gradient(to right, rgba(30, 75, 115, 1), rgba(255, 255, 255, 0));
background-repeat: no-repeat,
no-repeat,
no-repeat;
background-position: bottom right,
left,
right;
}
.box:hover {
background-repeat: repeat,
no-repeat,
no-repeat;
background-position: bottom right,
bottom,
right;
}
<div class="box"></div>
或者,您可以使用CSS变量来定义所需的值,并且可以在以后更改这些值,而无需更改其他值:
.box {
width:200px;
height:200px;
background-image: url(https://mdn.mozillademos.org/files/11305/firefox.png),
url(https://mdn.mozillademos.org/files/11307/bubbles.png),
linear-gradient(to right, rgba(30, 75, 115, 1), rgba(255, 255, 255, 0));
background-repeat: var(--r,no-repeat),
no-repeat,
no-repeat;
background-position: bottom right,
var(--p,left),
right;
}
.box:hover {
--r:repeat;
--p:right;
}
<div class="box"></div>
您也可以使用JS执行相同的操作:
document.querySelector(".box").addEventListener('click',function(e) {
e.target.style.setProperty('--r','repeat');
e.target.style.setProperty('--p','right');
})
.box {
width:200px;
height:200px;
background-image: url(https://mdn.mozillademos.org/files/11305/firefox.png),
url(https://mdn.mozillademos.org/files/11307/bubbles.png),
linear-gradient(to right, rgba(30, 75, 115, 1), rgba(255, 255, 255, 0));
background-repeat: var(--r,no-repeat),
no-repeat,
no-repeat;
background-position: bottom right,
var(--p,left),
right;
}
<div class="box"></div>
https://stackoverflow.com/questions/51032837
复制相似问题