如何使用div + CSS +JS 来模拟滑动条?
我也踩过这个坑( 1 )
节点操作
详细描述
截图
代码
编辑于2024-11-23
-
[成都|荣耀师兄]JS-胡力耘0
先写出基本的HTML结构
<div class="slide"><div class="slide__bar"></div><div class="slide__bar-active"></div><div class="slide__thumb"></div></div>CSS样式如下:
.slide {position: relative;display: inline-block;}.slide__bar {width: 500px;height: 10px;border-radius: 5px;background-color: rgb(243, 216, 127);}.slide__bar-active {position: absolute;top: 50%;transform: translateY(-50%);z-index: 10;height: 10px;width: 500px;border-radius: 5px;background-color: rgb(255, 0, 212);}.slide__thumb {position: absolute;top: 50%;left: 50px;transform: translateY(-50%);z-index: 20;width: 56px;height: 34px;border-radius: 5px;background-image: url(../resource/slide.png);background-size: cover;}CSS部分不赘述,以上的步骤完成了外观部分。
现在开始实现功能部分。
首先我们要来使滑块能够被拖动,关于拖动,有三个事件。
mousedown, mousemove, mouseup
slideThumb.onmousedown = function () {//获取初始鼠标点击下去的位置var initX = event.clientX;var left = slideThumb.getAttribute("style");//获取滑块的left属性值并转化为number类型var reg = /\d+/;var leftNumber = parseInt(reg.exec(left)[0]);//滑动事件document.onmousemove = function () {//计算移动的距离var distance = leftNumber + event.clientX - initX;slideThumb.setAttribute("style", "left:" + distance + "px");}document.onmouseup = function () {document.onmousemove = null;document.onmouseup = null;}}以上就是拖动滑块的实现。
接下来再拖动事件的内部进行修改。
//set boundray and thumb widthvar maxBoudray = 400;var thumbWidth = 56;//获取滑块、滑动条、填充条元素var slideBarActive = document.getElementsByClassName("slide__bar-active")[0];var slideThumb = document.getElementsByClassName("slide__thumb")[0];var slideBar = document.getElementsByClassName("slide__bar")[0];//initialize 初始化 设定默认值slideBar.setAttribute("style", "width:" + maxBoudray + "px;background-color:transparent;border:1px solid #999");slideThumb.setAttribute("style", "left:60px;")slideBarActive.setAttribute("style", "width:" + (slideThumb.offsetLeft + thumbWidth / 2) + "px");//电脑端鼠标事件slideThumb.onmousedown = function () {//获取初始鼠标点击下去的位置var initX = event.clientX;var left = slideThumb.getAttribute("style");//获取滑块的left属性值并转化为number类型var reg = /\d+/;var leftNumber = parseInt(reg.exec(left)[0]);//滑动事件document.onmousemove = function () {//计算移动的距离var distance = leftNumber + event.clientX - initX;//检测是否超出滑动条边界if (distance < 0) {distance = 0;} else if (distance > maxBoudray - thumbWidth / 2) {distance = maxBoudray - thumbWidth / 2;}//设置滑块的left值slideThumb.setAttribute("style", "left:" + distance + "px");//设置填充条部分的宽度slideBarActive.setAttribute("style", "width:" + (slideThumb.offsetLeft + thumbWidth / 2) + "px");}document.onmouseup = function () {document.onmousemove = null;document.onmouseup = null;}}编辑于2018-06-23
- 去第 页