我正在使用background-image: linear-gradient
制作动画,但可悲的是,CSS无法为渐变属性动画。因此,我提出了background-postion
解决方案。这个想法是创建一个元素大小为3倍的background-image
,并在过渡期间移动background-postion
。
要设置background-position
,我可以使用px
或%
,但是它们的工作原理确实不同。请看下面的例子
let elementPixel = document.getElementById('background-pixel');
let elementPercent = document.getElementById('background-percent');
let inputPixel = document.getElementById('range-pixel');
let inputPercent = document.getElementById('range-percent');
let labelPixel = document.getElementById('label-pixel');
let labelPercent = document.getElementById('label-percent');
inputPixel.addEventListener('input', (event) => {
elementPixel.style.backgroundPosition = `0 ${inputPixel.value}px`;
labelPixel.innerHTML = `background-position: ${inputPixel.value}px`
})
inputPercent.addEventListener('input', (event) => {
elementPercent.style.backgroundPosition = `0 ${inputPercent.value}%`;
labelPercent.innerHTML = `background-position: ${inputPercent.value}%`
})
.background-animateable {
margin: 50px;
border: solid 1px black;
width: 200px;
height: 200px;
background-image: linear-gradient(to bottom, white 0%, red 32.9%, yellow 33%, yellow 34%, red 34.1%, green 65.9%, yellow 66%, yellow 67%, green 67.1%, blue 100%);
background-repeat: no-repeat;
}
.wrapper1 {
display: flex;
align-items: center
}
.wrapper2 {
display: flex;
width: 100%
}
.wrapper2 .background-animateable {
background-size: 100% 300%;
}
.parent {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.parent input {
margin-top: 10px;
}
#background-pixel {
background-position: 0 0px;
}
#background-percent {
background-position: 0 0%;
}
<div class="wrapper1">
<div class="background-animateable"> </div>
←Origin background look like this
</div>
<div class="wrapper2">
<div class="parent">
<div class="background-animateable" id="background-pixel"></div>
<label id="label-pixel">background-position: 0 0px</label>
<input type="range" id="range-pixel" name="volume" min="-600" value="0" max="600" />
</div>
<div class="parent">
<div class="background-animateable" id="background-percent"></div>
<label id="label-percent">background-position: 0 0%</label>
<input type="range" id="range-percent" name="volume" min="-200" value="0" max="200" />
</div>
</div>
只需玩摘录。
如果我们在background-postion
中设置px
,则负值表示背景将保持高于元素,并且我们可以看到background-image
的其他部分,正值将使背景低于元素,因此我们将看到空白的background-color
。这是当之无愧的行为。
当我们在background-postion
中设置%
时,我想到的第一件事是它将与'px'相同,并且距离将基于背景大小。但不是!如果要查看背景图像的33%->66%
,则需要设置 background-position: 0 50%
,同时px
中的值为 background-position: 0 -200px
。发生了什么?关于符号和关于200px ~ 33.33%
而非background-image
的高度50%
的值是相反的。嗯,这真让我感到困惑。
问题是:background-postion: ...%
如何与background-image
一起使用?
请注意:如果我们将linear-gradient
更改为图片url
,其行为将仍然相同