如何阻止滑块根据 div 的高度改变其位置?

How to stop a slider from changing its position according to the height of a div?

let Container = document.getElementById("Container1");
let slider = document.getElementById("slider1");

Container.setAttribute("style", "height: " + slider.value + "px");

slider.oninput = function() {
  Container.setAttribute("style", "height: " + this.value + "px");
};
.container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

#Container1 {
  width: 160px;
  height: 90px;
  border: 1px solid #000;
}

#slider1 {
  -webkit-appearance: none;
  background-color: black;
  width: 90px;
  height: 1px;
  transform: translateX(-50%) translateX(0.5cm) rotate(90deg);
  transform-origin: center;
}
<div class="container">
  <div id="Container1"></div>
  <input type="range" min="0" max="90" id="slider1" />
</div>

在这里,滑块似乎随着它旁边的 div 元素的高度而改变它的位置。为什么会这样?如何阻止它?在我的尝试中,我尝试设置 .container {height: 90px;} 并且原始问题得到解决,但发生了一些奇怪的事情。为什么会这样?谢谢!

let Container = document.getElementById("Container1");
let slider = document.getElementById("slider1");

Container.setAttribute("style", "height: " + slider.value + "px");

slider.oninput = function() {
  Container.setAttribute("style", "height: " + this.value + "px");
};

滑块会更改容器的高度,因为您将容器高度属性设置为滑块值。删除这些 javascript 行,滑块将停止更改容器的高度。

javascript 代码侦听滑块上的输入,当移动滑块时,容器高度属性将设置为 this.value。在这种情况下 this 指的是滑块。

试试这个

我把高度放在主要部分 div 所以所有内容都保持在静态 div。

transform: translateY(-50%) translateY(1.2cm)将Y变换为1.2cm

align-items: start; 因此项目位于容器的开头

let Container = document.getElementById("Container1");
let slider = document.getElementById("slider1");

Container.setAttribute("style", "height: " + slider.value + "px");

slider.oninput = function() {
  Container.setAttribute("style", "height: " + this.value + "px");
};
.container {
    display: flex;
    justify-content: flex-start;
    align-items: start;
    height: 90px;
}

#Container1 {
  width: 160px;
  height: 90px;
  border: 1px solid #000;
}

#slider1 {
    -webkit-appearance: none;
    background-color: black;
    width: 90px;
    height: 1px;
    transform: translateX(-50%) translateX(0.5cm) translateY(-50%) translateY(1.2cm) rotate(90deg);
    transform-origin: center;
}
<div class="container">
  <div id="Container1"></div>
  <input type="range" min="0" max="90" id="slider1" />
</div>