仅在激活“ onmousedown”事件时激活“ onmousemove”事件

时间:2019-01-20 23:13:09

标签: javascript css

在发现了对类型范围的输入进行样式设置的困难之后,我最好还是简单地使用css创建一个并隐藏原始内容。我正在尝试制作音量滑块,但我认为我不完全了解如何连接 onmousemove onmousedown 。我尝试关注以下帖子

How to connect onmousemove with onmousedown?

但是我的 volumeSlider 函数-被注释掉的javascript代码-仍然无法运行;

我想要的是 onmousemove 仅在 onmousedown 上被激活,而不仅仅是通过移动鼠标来激活。

const volume_div = document.querySelector('.volume');
const volumeBtn_div = document.querySelector('.volume-button');

function volumeClick(event) {
  let x = event.offsetX;
  volume_div.style.width = (Math.floor(x) + 10) + 'px';
}

/*
volumeBtn_div.onmousedown = function() {
  volumeBtn_div.onmousemove = volumeSlide;
};

function volumeSlide(event) {
  let x = event.offsetX;
  volume_div.style.width = Math.floor(x) + 'px';
}*/
body {
  background-color: #2a2a2a;
}

.volume-range {
  margin-top: 80px;
  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="volume-range" onclick="volumeClick(event)">
    <div class="volume">
      <div class="volume-button"></div>
    </div>
  </div>

1 个答案:

答案 0 :(得分:4)

如果我正确理解了您的问题,我认为您可以将标志设置为onmousedown并将其重置为onmouseup。像这样:

let mouseIsDown = false;
volumeBtn_div.onmousedown = function() { mouseIsDown = true };
volumeBtn_div.onmouseup = function() { mouseIsDown = false };
volumeBtn_div.onmousemove = volumeSlide;
function volumeSlide(event) {
  if(mouseIsDown){
    let x = event.offsetX;
    volume_div.style.width = Math.floor(x) + 'px';
  }
}  

...


为回应您的评论,此类似示例可在Chrome中运行。我更改了EventListener语法。它应该使您走上正确的轨道。

<!DOCTYPE html>
<html>
<head>
  <style>
    div { width: 200px; height: 100px; border: 1px solid black; }
  </style>
</head>
<body>
  <div id="input"></div>
  <p id="output"></p>
  <script>
    const input = document.getElementById("input");
    const output = document.getElementById("output");
    let mouseIsDown = false;
    input.addEventListener("mouseup", up);
    input.addEventListener("mousedown", down);
    input.addEventListener("mousemove", slide);

    function down(){ mouseIsDown = true; }
    function up(){ mouseIsDown = false; }
    function slide(e) {
      if(mouseIsDown){
        var x = e.clientX;
        var pos = "pos: " + x;
        output.innerHTML = pos;
      }
    }
  </script>
</body>
</html>