<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="slider" class="slider">
<div class="thumb"></div>
</div>
<script>
let thumb = slider.querySelector('.thumb');
thumb.onmousedown = function(event) {
event.preventDefault();
let shiftX = event.clientX - thumb.getBoundingClientRect().left;
//from the start of the leftmost side to the exact mouse x
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
function onMouseMove(event) {
let newLeft = event.clientX - shiftX - slider.getBoundingClientRect().left;
//the pointer is out of slider=> lock the thumb within the boundaries
if(newLeft < 0){
newLeft = 0;//so that it doesnt go out of the bar leftside
}
let rightEdge = slider.offsetWidth - thumb.offsetWidth;
if (newLeft > rightEdge) {
//if the mouse pointer go out of the range to right side
newLeft = rightEdge; //then block it lol what else
}
thumb.style.left = newLeft + 'px';
//after all that, apply the value to the style
}
function onMouseUp(){
document.removeEventListener('mouseup', onMouseUp);
document.removeEventListener('mousemove', onMouseMove);
}
}
thumb.ondragstart = function() {
return false;
}
</script>
</body>
</html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="slider" class="slider">
<div class="thumb"></div>
</div>
<script>
let thumb = slider.querySelector('.thumb');
thumb.onmousedown = function(event) {
event.preventDefault();
let shiftX = event.clientX - thumb.getBoundingClientRect().left;
//from the start of the leftmost side to the exact mouse x
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
function onMouseMove(event) {
let newLeft = event.clientX - shiftX - slider.getBoundingClientRect().left;
//the pointer is out of slider=> lock the thumb within the boundaries
if(newLeft < 0){
newLeft = 0;//so that it doesnt go out of the bar leftside
}
let rightEdge = slider.offsetWidth - thumb.offsetWidth;
if (newLeft > rightEdge) {
//if the mouse pointer go out of the range to right side
newLeft = rightEdge; //then block it lol what else
}
thumb.style.left = newLeft + 'px';
//after all that, apply the value to the style
}
function onMouseUp(){
document.removeEventListener('mouseup', onMouseUp);
document.removeEventListener('mousemove', onMouseMove);
}
}
thumb.ondragstart = function() {
return false;
}
</script>
</body>
</html>
댓글
댓글 쓰기