The content of this article is about how to use javascript css to implement custom dragging progress bar (code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Customize the draggable progress bar, as shown below:
The code is divided into three parts
HTML
<body> <div id="demo"> <div class="progress"> <div class="progress-bar"> <div class="progress-thumb"></div> </div> </div> </div> </body>
CSS
#demo { width: 600px; height: 100px; margin: 100px auto; display: flex; align-items: center; } #demo .progress { width: 100%; height: 6px; border-radius: 3px; background: #F1F5FD; } #demo .progress .progress-bar { width: 40%; height: 100%; border-radius: 3px; background: #0072FF; } #demo .progress .progress-bar .progress-thumb { width: 14px; height: 14px; border-radius: 50%; background: #FFFFFF; box-shadow: 0 0 15px 5px #0072FF; float: right; position: relative; left: 7px; top: -5px; }
At this point, the custom style has been basically implemented. You only need to change the width of .progress-bar to display different progress; next, add Drag event
JavaScript
<script> var slider = { use: function(id) { var self = this; self.slider = document.getElementById(id); self.bar = self.slider.querySelector('.progress-bar'); self.thumb = self.slider.querySelector('.progress-thumb'); self.slider.addEventListener('mousedown', function(e) { if (e.button == 0) { // 判断点击左键 self.mDown = true; self.beginX = e.offsetX; self.positionX = e.offsetX; self.beginClientX = e.clientX; self.sliderLong = parseInt(self.getStyle(self.slider, 'width')); var per = parseInt(self.positionX / self.sliderLong * 100); self.bar.style.width = per + '%'; } }); document.addEventListener('mousemove', function(e) { if (self.mDown) { var moveX = e.clientX - self.beginClientX; self.positionX = (self.beginX + moveX > self.sliderLong) ? self.sliderLong : (self.beginX + moveX < 0) ? 0 : self.beginX + moveX; var per = parseInt(self.positionX / self.sliderLong * 100); self.bar.style.width = per + '%'; } }); document.addEventListener('mouseup', function(e) { if (e.button == 0) { self.mDown = false; } }); }, getStyle: function(obj,styleName){ // 获取元素样式的方法 if(obj.currentStyle){ return obj.currentStyle[styleName]; }else{ return getComputedStyle(obj,null)[styleName]; } } }; slider.use('demo'); </script>
Instructions:
1. Bind the mousedown event to the wrapping layer of the progress bar instead of the progress bar itself. This is The design is based on the effects of mainstream video players in order to optimize the user experience;
2. JS is written in pure native syntax. If you use JQuery, it can simplify the acquisition of selectors and CSS styles;
3. This article uses clientX to calculate the movement of the mouse outside the scroll bar.
The above is the detailed content of How to use javascript+css to implement a custom drag progress bar (code). For more information, please follow other related articles on the PHP Chinese website!