原生js javascript 实现进度条拖动---移动端

最近的需求有个简单的移动端页面,需要在页面中实现一个进度条的拖动,因为没引入什么框架,所以只能原生JavaScript手写了,
效果图:
原生js javascript 实现进度条拖动---移动端_第1张图片
代码:这些代码可以复制到本地一个html文件中,直接双击打开,但是注意:因为是针对移动端的,所以要在浏览器的手机模式下才能用!!!
原生js javascript 实现进度条拖动---移动端_第2张图片

DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Documenttitle>
  head>
  <body>
    <div class="wrap" id="wrap">
      <div class="proportion" id="proportion">div>
      <span class="box" id="box">span>
    div>
    <p>百分比: <span id="number">span>p>
  body>

  <script type="text/javascript" src="jquery.min.js">script>
  <script type="text/javascript">
    let wrap = document.getElementById("wrap");
    let box = document.getElementById("box");

    var touchStart_x = null,
      touchStart_y = null,
      touchMove_x = null,
      touchMove_y = null,
      boxStartX = null,
      boxStartY = null;

    $("#box").on("touchstart", function (e) {
      touchStart_x = e.targetTouches[0].pageX;

      touchStart_y = e.targetTouches[0].pageY;

      boxStartX = $("#box").position().left;

      boxStartY = $("#box").position().top;
    });
    $("#box").on("touchmove", function (e) {
      touchMove_x = e.targetTouches[0].pageX - touchStart_x;

      touchMove_y = e.targetTouches[0].pageY - touchStart_y;

      let leftNum = boxStartX + touchMove_x;
      if (leftNum < 0) {
        leftNum = 0;
      } else if (leftNum > 285) {
        leftNum = 285;
      }

      $("#proportion").css({
        width: leftNum + 15,
      });

      // 计算百分比
      let allWidth = $("#wrap").width();
      if ((boxStartX + touchMove_x) <= 0) {
        let txt = "0%";
        $("#number").html(txt);
      }
      else if( (boxStartX + touchMove_x) >= 285){
        let txt = (((leftNum + 15) / allWidth) * 100).toFixed(0) + "%";
        $("#number").html(txt);
      }
      else{
        let txt = ((leftNum / allWidth) * 100).toFixed(0) + "%";
        $("#number").html(txt);
      }

      $("#box").css({
        left: leftNum,
      });
    });
  script>
  <style>
    *{
      box-sizing: border-box;
    }
    html {
      width: 100%;
      height: 100%;
      overflow: hidden;
    }
    body{
      padding: 20px;
      box-sizing: border-box;
    }

    .wrap {
      position: relative;
      width: 300px;
      height: 10px;
      background-color: #eee;
      border-radius: 5px;
    }
    .proportion {
      width: 0;
      height: 10px;
      background-color: rgb(93, 233, 64);
      border-radius: 5px;
    }
    .box {
      position: absolute;
      left: 0;
      top: -3px;
      width: 15px;
      height: 15px;
      background-color: orange;
      border-radius: 50%;
      cursor: pointer;
    }
  style>
html>

你可能感兴趣的:(javascript,移动端,进度条)