onmouseup 事件对滑块无法正常工作 [英] onmouseup event does not work correctly to the slider
问题描述
我创建了一个简单的 JS 滑块,它通过 eventListener onmousedown
对点击做出反应.但是,如果您运行下面的代码,您会看到,如果我们离开滚动区域 scrollContainer,
toddler
不会被 eventListener onmouseup
正确停止代码> 按住鼠标左键.toddler
将在下面松散滚动,我们将直接点击他.
需要什么 - toddler
必须在我们释放鼠标左键时停止(在结束 eventListener onmousedown
之后).
我将不胜感激.
var scrollLine = document.getElementById('scrollBar');var scrollTog = document.getElementById('toddler');函数让移动(事件){var coordsHelp = getRealCoords(幼儿);var shiftX = event.pageX - coordsHelp.left;获取坐标(事件);函数 getRealCoords(幼儿){var box = toddler.getBoundingClientRect();返回 {左:box.left + pageXOffset}};函数 getCoords(event) {var currentPosition = event.pageX - shiftX;如果(当前位置 >= 300){toddler.style.left = 300 + 'px';} else if (currentPosition <= 104) {toddler.style.left = 104 + 'px';} 别的 {toddler.style.left = currentPosition + 'px';}};scrollContainer.onmousemove = 函数(事件){获取坐标(事件);控制台日志();};toddler.ondragstart = 函数(){返回假;};toddler.onmouseup = 函数(){scrollContainer.onmousemove = null;scrollContainer.onmouseup = null;toddler.onmouseup = null;toddler.onmousemove = null;返回假;};}toddler.addEventListener('mousedown',letsMove);
<头><meta charset="utf-8"><风格>#scrollContainer {宽度:400px;高度:200px;边框:1px 纯灰色;边框半径:4px;}#滚动条{宽度:200px;高度:5px;背景颜色:灰色;边框:1px 纯灰色;边框半径:4px;保证金最高:24%;左边距:24%;}#学步的儿童 {宽度:10px;高度:25px;位置:绝对;边距顶部:-11px;背景颜色:蓝色;边框:1px 纯灰色;边界半径:2px;光标:指针;}</风格>头部><身体><div id="scrollContainer"><div id="scrollBar"><div id="幼儿"></div>
<脚本></html>
解决这个问题的方法非常简单.当鼠标不在幼儿"上方时,您没有触发 onmouseup
的原因实际上是因为鼠标不在幼儿"上方.(鼠标指针未触及的对象不会触发鼠标事件).
只需将侦听器更改为整个窗口(在真实"代码中,您可能需要添加一个保护,以便您知道哪个滑块正在等待鼠标抬起).
var scrollLine = document.getElementById('scrollBar');var scrollTog = document.getElementById('toddler');函数让移动(事件){var coordsHelp = getRealCoords(幼儿);var shiftX = event.pageX - coordsHelp.left;获取坐标(事件);函数 getRealCoords(幼儿){var box = toddler.getBoundingClientRect();返回 {左:box.left + pageXOffset}};函数 getCoords(event) {var currentPosition = event.pageX - shiftX;如果(当前位置 >= 300){toddler.style.left = 300 + 'px';} else if (currentPosition <= 104) {toddler.style.left = 104 + 'px';} 别的 {toddler.style.left = currentPosition + 'px';}};scrollContainer.onmousemove = 函数(事件){获取坐标(事件);控制台日志();};toddler.ondragstart = 函数(){返回假;};/* toddler.onmouseup = function() { */window.onmouseup = 函数(){scrollContainer.onmousemove = null;scrollContainer.onmouseup = null;toddler.onmouseup = null;toddler.onmousemove = null;返回假;};}toddler.addEventListener('mousedown',letsMove);
<头><meta charset="utf-8"><风格>#scrollContainer {宽度:400px;高度:200px;边框:1px 纯灰色;边框半径:4px;}#滚动条{宽度:200px;高度:5px;背景颜色:灰色;边框:1px 纯灰色;边框半径:4px;保证金最高:24%;左边距:24%;}#学步的儿童 {宽度:10px;高度:25px;位置:绝对;边距顶部:-11px;背景颜色:蓝色;边框:1px 纯灰色;边界半径:2px;光标:指针;}</风格>头部><身体><div id="scrollContainer"><div id="scrollBar"><div id="幼儿"></div>
<脚本></html>