簡體   English   中英

JavaScript中的自定義音量滑塊

[英]custom volume slider in javascript

我正在嘗試改善前段時間的音量滑塊代碼。 我遇到的問題如下。

問題

  1. 當您單擊音量按鈕並第一次拖動它時,音量按鈕會跳到起點。
  2. 由於出現第一個錯誤,因此拖動鼠標時鼠標光標不會在音量按鈕的中心對齊。

這可能是由於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> 

您需要將mousemove Event設置為音量按鈕容器,而不是本身,然后添加pointer-events: none; 音量按鈕,因此它沒有自己單獨的鼠標坐標。

查看工作演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM