动画效果:
JS分析:
function initInputs() { // 获取 input:range NodeList let allInputs = document.body.querySelectorAll(".bar-input"); for (let i = 0; i < allInputs.length; i++) { // 获取 单独的 input let input = allInputs[i]; // 获取 单独的 input 父节点的 ID let barId = input.parentNode.id; // 在 head 标签添加 style 标签 let styleEl = document.head.appendChild(document.createElement("style")); if (i == allInputs.length - 1) { //set indicator 设置第三个进度的值 89% let indicator=input.parentNode.querySelector('.bar .indicator'); setBarIndicator(barId, input, styleEl, indicator); // 方法在 oninput onchange 事件触发时调用,并传递参数 input.oninput = setBarIndicator.bind(this, barId, input, styleEl, indicator); input.onchange = setBarIndicator.bind(this, barId, input, styleEl, indicator); } else { setBar(barId, input, styleEl); input.oninput = setBar.bind(this, barId, input, styleEl); input.onchange = setBar.bind(this, barId, input, styleEl); } } } function setBar(barId, input, styleEl) { // 在 style 标签中添加 进度 width styleEl.innerHTML = "#" + barId + " .bar-face.percentage:before {width:" + input.value + "%;}"; } function setBarIndicator(barId, input, styleEl, indicatorEl) { // 在 style 标签中添加 进度 width styleEl.innerHTML = "#" + barId + " .bar-face.percentage:before {width:" + input.value + "%;}"; // 显示的 89% 的样式 indicatorEl.style.marginLeft = (input.value - 10) + '%'; indicatorEl.textContent = input.value + '%'; } initInputs();
总结
- css 使用 transform 来“画”长方体
- 使用 input:range 来完成进度
- 使用 input 的 onchange 和 oninput 事件来控制进度