SOURCE

console 命令行工具 X clear

                    
>
console
// 第一题
var slider = document.createElement('div')
slider.className = 'slider'

var track = document.createElement('div')
track.className = 'slider-track'

var thumb = document.createElement('div')
thumb.className = 'slider-thumb'

slider.appendChild(track).appendChild(thumb);
document.body.appendChild(slider);

// 第二题
slider.style.setProperty("--percent", 50);

// 第三题
const { width, left } = slider.getBoundingClientRect();
document.getElementsByClassName('slider-track')[0].addEventListener("click", function(e) {
  const percent = (e.pageX -left) / width;
  slider.style.setProperty("--percent", percent * 100);
});

// 第四题

var thumbMove = (e) => {
  console.log(e.pageX)
    let dis = e.pageX - left
    let len = Math.min(Math.max(0, dis), width)
    console.log('len',len)
    console.log('len/width*100', len/width * 100)
    slider.style.setProperty('--percent', len / width * 100)
}
document.getElementsByClassName('slider-thumb')[0].addEventListener('mousedown', (e) => {
    document.addEventListener('mousemove', thumbMove)
})

window.addEventListener('mouseup', (e) => {
    document.removeEventListener('mousemove', thumbMove)
})
.slider {
    padding: 5px 0;
    position: relative;
    margin: 30px 10%;
    --percent: 0;
}
.slider-track {
    display: block;
    width: 100%; height: 6px;
    background-color: lightgray;
    border: 0; padding: 0;
}
.slider-track::before {
    content: '';
    display: block;
    height: 100%;
    background-color: skyblue;
    width: calc(1% * var(--percent));
}
.slider-thumb {
    position: absolute;
    width: 16px; height: 16px;
    border: 0; padding: 0;
    background: #fff;
    box-shadow: 0 0 0 1px skyblue;
    border-radius: 50%;
    left: calc(1% * var(--percent)); top: 0;
    margin: auto -8px;
}