我正在尝试改善前一阵子的音量滑块代码。我遇到的问题如下。
问题
这可能是由于event.offsetX
造成的。
第一次单击并移动音量按钮时,event.offsetX
会获得在音量按钮上单击的位置的偏移量到“音量按钮的开始”。 >
为解决此问题,我添加了变量firstClicked
。但是,这不能解决问题。
const volume = document.querySelector('.volume');
const volumeRange = document.querySelector('.volume-range');
const volumeContainer = document.querySelector('.volume-container');
const volumeBtn = document.querySelector('.volume-button');
const volumeRangeWidth = volumeRange.getBoundingClientRect().width; // This will be the volume limit (100%)
/*volumeContainer.addEventListener("click", volumeClick);
function volumeClick(event) {
let x = Math.floor(event.offsetX);
if (x < 0) x = 0; // check if it's too low
if (x > volumeRangeWidth) x = volumeRangeWidth; // check if it's too high
volume.style.width = (x + 10) + 'px';
}
*/
let mouseIsDown = false;
window.addEventListener("mouseup", up);
volumeBtn.addEventListener("mousedown", down);
volumeContainer.addEventListener("mousemove", volumeSlide);
function down() {
mouseIsDown = true;
}
function up() {
mouseIsDown = false;
firstClick = true;
}
let firstClick = true; // this doesn't work
function volumeSlide(event) {
if (mouseIsDown && !firstClick) {
let x = Math.floor(event.offsetX - event.currentTarget.getBoundingClientRect().left);
if (x < 0) x = 0; // check if it's too low
if (x > volumeRangeWidth) x = volumeRangeWidth; // check if it's too high
volume.style.width = (x + 10) + 'px';
}
// "firstClick" ignores the offset on the first click as it gives the offset of the volume button
firstClick = false;
}
body {
background-color: #2a2a2a;
}
.volume-container {
padding: 40px 0px;
margin: 0px 20px;
background-color: dodgerblue;
}
.volume-range {
height: 5px;
width: 250px;
background: #555;
border-radius: 15px;
}
.volume-range>.volume {
height: 5px;
width: 50px;
background: #2ecc71;
border: none;
border-radius: 10px;
outline: none;
position: relative;
}
.volume-range>.volume>.volume-button {
width: 20px;
height: 20px;
border-radius: 20px;
background: #FFF;
position: absolute;
right: 0;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
outline: none;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Volume</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
</head>
<body>
<div class="" style="padding-left:10px; background-color:dodgerblue;">
<div class="volume-container">
<div class="volume-range">
<div class="volume">
<div class="volume-button"></div>
</div>
</div>
</div>
</div>
</body>
</html>
答案 0 :(得分:1)
您需要将mousemove
事件设置为音量按钮容器,而不是本身,然后将pointer-events: none;
添加到音量按钮,以使其没有自己的单独鼠标坐标。