It is not at all possible to limit the movement of the marker on the slider.

const mark = document.getElementById('marker'); const slider = document.getElementById('slider'); mark.onmousedown = function(e) { let value = e.pageX - slider.offsetLeft - (mark.offsetWidth / 2); function moveAt(e) { mark.style.left = e.pageX - slider.offsetLeft - (mark.offsetWidth / 2) + 'px'; } document.onmousemove = function (e) { if(value > 0 && value < 380 ){ // value сравнивается сначала с left: 0px , потом с left: 380px, сам маркер задан абсолютным позиционированием moveAt(e); console.log(value); } else{ console.log("Что-то сделать"); // проблема в том что else срабатывает после отпускания маркера } } document.onmouseup = function () { document.onmousemove = null; mark.onmouseup = null; } } 
 #slider{ position: relative; width: 400px; height: 40px; background: #d5dbe5; margin: 30px auto; } #marker{ position: absolute; width: 20px; height: 40px; background: gray; } 
 <div id="slider"> <div id="marker"></div> </div> 

    1 answer 1

    You calculate once

    let value = e.pageX - slider.offsetLeft - (mark.offsetWidth / 2); and then compare this value with limiters. It must be calculated every time so that it is relevant.

     const mark = document.getElementById('marker'); const slider = document.getElementById('slider'); mark.onmousedown = e => { let value = e.pageX - slider.offsetLeft - (mark.offsetWidth / 2); const moveAt = value => { mark.style.left = value + 'px'; } document.onmousemove = e => { value = e.pageX - slider.offsetLeft - (mark.offsetWidth / 2); if(value > 0 && value < 380 ){ moveAt(value); }else{ moveAt(value>0?380:0); } } document.onmouseup = () => { document.onmousemove = null; mark.onmouseup = null; } } 
     #slider{ position: relative; width: 400px; height: 40px; background: #d5dbe5; margin: 30px auto; } #marker{ position: absolute; width: 20px; height: 40px; background: gray; } 
     <div id="slider"> <div id="marker"></div> </div> 

    • Tell me please, and how to make the color fill for the slider slider? - LutiyCsharp