【发布时间】:2022-01-22 17:43:16
【问题描述】:
我想用 CSS & JS 和 HR HTML 元素制作动态效果:这个想法是像这样水平制作 4 行:
并通过添加 range 类型的输入 使其动态化,并根据 input range 的值使它们在宽度上增长和缩小!
到目前为止我尝试过的:
document
.querySelector('input[type="range"]')
.addEventListener("input", (e) => {
document.querySelectorAll(".line").forEach((line) => {
line.style.width = line.offsetWidth + 10 + "px";
const marginOnLeft = window
.getComputedStyle(line)
.getPropertyValue("margin-left")
.slice(0, -2); //remove "px"
line.style.marginLeft =
Number(marginOnLeft) + 100 / Number(marginOnLeft) + "px";
});
});
.lines {
position: relative;
}
.line {
position: absolute;
}
hr {
background-color: black;
border-radius: 5px;
}
.line1 {
width: 500px;
height: 3px;
margin-left: 0;
margin-top: 5px;
}
.line2 {
width: 400px;
height: 6px;
margin-left: 50;
margin-top: 5px;
}
.line3 {
width: 300px;
height: 8px;
margin-left: 100;
margin-top: 5px;
}
.line4 {
width: 200px;
height: 10px;
margin-left: 150;
}
input[type="range"] {
margin-top: 70px;
}
<div class="lines">
<hr class="line line1" />
<hr class="line line2" />
<hr class="line line3" />
<hr class="line line4" />
</div>
<div>
<input type="range" name="" id="" value="10" />
</div>
如何跟踪用户的input range增加或减少;根据其值所有水平线将动态变宽或变窄!更重要的是,我会根据input range value 动态地增加或减少margin-left,我做得对还是使用CSS variables;欢迎提出任何建议并更加感谢!
【问题讨论】:
标签: javascript html css margin css-variables