当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS实现音量控制拖动

JS实现音量控制拖动

2020年03月09日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了js实现音量控制拖动的具体代码,供大家参考,具体内容如下

描述:

js——实现音量控制拖动

    1)、有底条,有拖拽按钮
    2)、设置最小和最大值
    3)、拖动定位后,抛出事件当前的所在值

效果:

实现:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>title</title>
  <style>
    #all {
      width: 500px;
      height: 86px;
      margin: 100px auto;
      position: relative;
    }
 
    #bar {
      width: 500px;
      height: 20px;
      border-radius: 10px;
      background: #9acfea;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
      cursor: pointer;
    }
 
    #box {
      width: 30px;
      height: 30px;
      background: #ec971f;
      position: absolute;
      bottom: 0;
      top: 0;
      margin: auto 0;
      border-radius: 50%;
      cursor: pointer;
      transition: left 0.1s linear 0s;
    }
  </style>
</head>
<body>
  <div id="all">
    <p>当前位置0%</p>
    <div id="bar">
      <div id="box"></div>
    </div>
  </div>
<script>
 
  var all=document.getelementbyid("all");//容器
  var p=document.queryselector("p");//进度百分比
  var bar=document.getelementbyid("bar");//进度显示条
  var box=document.getelementbyid("box");//进度按钮
 
  var boxl,newl,movel,mousex,left;
  var cha = bar.offsetwidth - box.offsetwidth;
  var index=0;//标记状态
 
  var evt=new event("change");//本身的事件
  init();
  function init() {
    box.addeventlistener("mousedown",mousedownclickhandler);
    document.addeventlistener("mousemove",mousemoveclickhandler)
    document.addeventlistener("mouseup",mouseupclickhandler);
    document.addeventlistener("change",changehandler);
    bar.addeventlistener("click",clickhandler);
  }
 
  function mousedownclickhandler(e) {
    index=1;
    boxl=box.offsetleft;
    mousex=e.clientx;//鼠标按下拖动的位置
  }
 
  function mousemoveclickhandler(e) {
    if(index===1){
      movel=e.clientx-mousex;//鼠标移动
      newl=boxl+movel;//left值
 
      //判断最小值与最大值
      if(newl<0){
        newl = 0;
      }
      if(newl>=cha){
        newl=cha;
      }
      // 改变left值
      box.style.left = newl + 'px';
      // 计算比例
      var bili = newl / cha * 100;
      p.textcontent = '当前位置' + math.ceil(bili) + '%';
      evt.elem=this;//当前指向 对象
      document.dispatchevent(evt);//朝谁发送 抛发
    }
  }
 
  function mouseupclickhandler(e) {
    index=0;
    evt.elem=this;//当前指向 对象
    document.dispatchevent(evt);//朝谁发送 抛发
  }
 
  function clickhandler(e) {
    left = e.clientx-all.offsetleft-box.offsetwidth/2;
    if(left<0){
      left=0;
    }
    if(left>=cha){
      left=cha;
    }
    box.style.left=left+'px';
    bili=left/cha*100;
    p.innerhtml='当前位置'+ math.ceil(bili)+'%';
    evt.elem=this;//当前指向 对象
    document.dispatchevent(evt);//朝谁发送 抛发
  }
 
  function changehandler(e) {
    console.log(e);
  }
</script>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网