背景位置:x%如何处理背景图像?

时间:2018-09-19 08:06:08

标签: css css3 background background-image linear-gradients

想法

我正在使用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>
  &larr;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,其行为将仍然相同

0 个答案:

没有答案