温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

js实现div色块拖动录制

发布时间:2020-10-25 23:49:02 来源:脚本之家 阅读:140 作者:SSSkyCong 栏目:web开发

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

描述:

实现一个div50*50的色块,拖动它生成一个轨迹,松手后,这个div会重复你刚才拖动的这个路径。

效果:

js实现div色块拖动录制<

js实现div色块拖动录制

代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    div
    {
      width: 50px;
      height: 50px;
      background-color: deepskyblue;
      position: absolute;
      border: 2px solid #656565;
    }
  </style>
  <script src="js/Method.js"></script>
</head>
<body>
<div></div>
  <script>
    var elem;
    var state=0;//当前的状态 初始0——拖动录制1——回放2
    var arr=[];//存放我们的行走路径的 数组
    var list=[];//存放我们的行走路径的 数组
 
    var index=0;
    init();
    function init() {
      elem=document.querySelector("div");
      Method.dragElem(elem);
      elem.addEventListener("mousedown",mouseHandler);
      elem.addEventListener("mouseup",mouseHandler);
      setInterval(animation,16);
    }
 
    function mouseHandler(e) {//当前的状态 初始0——拖动录制1——回放2
      if(e.type==="mousedown"){//鼠标按下
        state=1;
      }else if(e.type==="mouseup"){//鼠标抬起
        createElemShadow();
        state=2;
      }
    }
 
    function createElemShadow() {
      var bool=false;
      if(list.length===0) bool=true;
      for(var i=0;i<5;i++){
        if(bool)list.push(elem.cloneNode(false));
        list[i].style.opacity=1-i*0.2;
        document.body.appendChild(list[i])
      }
    }
    
    function animation() {
      if(!state) return;
      if(state===1){
        record();
      }else if(state===2){
        play();
      }
    }
    
    function record() {
      var rect=elem.getBoundingClientRect();
      arr.push({x:rect.x,y:rect.y});
    }
    
    
    function play() {
     /* if(index>=arr.length-1){
        state=0;
        return;
      }*/
      index++;
      var point=arr[index];
      if(point){
        elem.style.left=point.x+"px";
        elem.style.top=point.y+"px";
        elem.style.backgroundColor=Method.divColor();
      }
      var bool=false;
      for(var i=0;i<list.length;i++){
        if(!arr[index-i*2]) continue;
        list[i].style.left=arr[index-i*2].x+"px";
        list[i].style.top=arr[index-i*2].y+"px";
        list[i].style.backgroundColor=Method.divColor();
        bool=true;
      }
      if(!bool){
        state=0;
        for(var j=0;j<list.length;j++){
          list[j].remove();
        }
      }
    }
  </script>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI