很多时候,不仅在在线商店的网站上,您还可以使用滑块进行过滤以选择一系列值。 在其中一个项目中,我还需要制作一个滑块。
首先想到的是找到现成的产品并将其粘贴到您的网站上。 然后我遇到了一个问题。 我发现JqueryUI.slider插件拒绝在某些移动设备上工作。 我无法确定问题所在(但不是真正的问题,我想在别人的代码中四处摸索),并决定制作自己的“自行车”。
我决定用纯JavaScript编写“自行车”,以免弄乱图书馆。 正如我的一个朋友说的:“连接越少,一切工作就越稳定”。
因此,我要做的第一件事就是建立这样一个简单的模型
<div class="filter"> <div> <span> 1</span> <div><number>10</number><number>50</number></div> <div class="slider"> <div class="block-min" onMouseDown="moveRange(this)" onTouchStart="moveRange(this)"></div> <div class="color-range"></div> <div class="block-max" onMouseDown="moveRange(this)" onTouchStart="moveRange(this)"></div> </div> </div> <div> <span> 2</span> <div><number>0</number><number>5</number></div> <div class="slider"> <div class="block-min" onMouseDown="moveRange(this)" onTouchStart="moveRange(this)"></div> <div class="color-range"></div> <div class="block-max" onMouseDown="moveRange(this)" onTouchStart="moveRange(this)"></div> </div> </div> </div>
在屏幕上看起来像这样

带有滑块的滑块本身位于“ slider”类的一个块中,其中还有2个以上的块:最小值滑块和最大范围值滑块。
他们描述了两个事件:
- onMouseDown-当我们用鼠标抓住滑块时触发;
- onTouchStart-当您在我们的滑块上触摸手指时,可在移动设备上使用。
滑块上方是一个带有两个数字的块-这是我们的最大值和最小值。
<div><number>0</number><number>5</number></div>
现在,让我们继续操作该函数本身,该函数在单击时被调用。
function moveRange (elem) {
getCoords函数允许我们获取元素的坐标和大小。
看起来如下。
function getCoords(elem) { let coords = elem.getBoundingClientRect(); return {
现在我们描述处理程序函数。
第一个函数是onMouseMove,当鼠标移动时调用。 仅在水平移动时才有效。
function onMouseMove(e) { e.preventDefault();
最后,“释放按钮”事件的处理程序功能或移动设备上的接触点丢失。 它将删除所有先前添加的事件,并将滑块保持在设置值。
function onMouseUp() { document.removeEventListener('mouseup', onMouseUp); document.removeEventListener('mousemove', onMouseMove); document.removeEventListener('touchend', onMouseUp); document.removeEventListener('touchmove', onMouseMove); }
当然,我们滑块的CSS样式
.filter { padding: 30px; width: 500px; } .filter>div { padding-top: 20px; display: -webkit-flex; display: -moz-flex; display: -ms-flex; display: -o-flex; display: flex; -webkit-flex-direction: column; -moz-flex-direction: column; -ms-flex-direction: column; -o-flex-direction: column; flex-direction: column; } .filter>div>div { display: -webkit-flex; display: -moz-flex; display: -ms-flex; display: -o-flex; display: flex; justify-content: space-between; } .filter .slider { margin-top: 10px; position: relative; height: 6px; background: #fff; border: 1px solid #000; } .filter .color-range { position: absolute; background: #a4a4a4; width: 97%; border: none; height: 6px; left: 15px; } .filter .block-min, .block-max { width: 15px; height: 25px; position: absolute; left: 0; top: -11.5px; background: #fff; border: 1px solid #000; border-radius: 4px; z-index: 1; } .filter .block-max{ left: 97%; }
在此处查看此滑块的工作版本 。
所有文件都可以从GitHub下载 。
使用愉快,工作简单!