📅  最后修改于: 2023-12-03 15:22:09.199000             🧑  作者: Mango
在 JavaScript 中制作步进器的过程中,有多种方法可以实现,其中一种是使用 2 个值(当前值和步长值)来实现。
currentValue
和 stepValue
,并分别将它们初始化为 0 和 1(或者你想要的初始值和步长值)。这两个值是步进器的核心。let currentValue = 0;
let stepValue = 1;
increase
和decrease
),分别对应增加和减少当前值。<button id="increase">Increase</button>
<button id="decrease">Decrease</button>
currentValue
增加 stepValue
,对于减少按钮,将 currentValue
减去 stepValue
。const increaseBtn = document.getElementById("increase");
const decreaseBtn = document.getElementById("decrease");
increaseBtn.addEventListener("click", () => {
currentValue += stepValue;
console.log(currentValue);
});
decreaseBtn.addEventListener("click", () => {
currentValue -= stepValue;
console.log(currentValue);
});
span
标签,并在每次更新 currentValue
时同时更新该元素的文本内容。<button id="increase">Increase</button>
<span id="current-value">0</span>
<button id="decrease">Decrease</button>
const currentValueSpan = document.getElementById("current-value");
increaseBtn.addEventListener("click", () => {
currentValue += stepValue;
currentValueSpan.textContent = currentValue;
});
decreaseBtn.addEventListener("click", () => {
currentValue -= stepValue;
currentValueSpan.textContent = currentValue;
});
<button id="increase">Increase</button>
<span id="current-value">0</span>
<button id="decrease">Decrease</button>
<script>
let currentValue = 0;
let stepValue = 1;
const increaseBtn = document.getElementById("increase");
const decreaseBtn = document.getElementById("decrease");
const currentValueSpan = document.getElementById("current-value");
increaseBtn.addEventListener("click", () => {
currentValue += stepValue;
currentValueSpan.textContent = currentValue;
});
decreaseBtn.addEventListener("click", () => {
currentValue -= stepValue;
currentValueSpan.textContent = currentValue;
});
</script>
这是一个简单的步进器示例,可以根据实际需求进行修改和扩展。