div元素的拖拽及回放效果

本例采用的是js事件捕获

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <style>
        .tuo{
            height:100px;
            width:100px;
            background-color:red;
            border-radius:50%;
            position:absolute;
        }

    </style>
    <script>
        onload=function(){
            var tuo=document.getElementsByClassName("tuo")[0];//获取要拖动的div元素
            var review=document.getElementsByClassName("review")[0];//要点击的回放
            var pos;//将pos定义为全局变量,才能不影响使用
            var post=[];//定义一个全局的空数组
            function move(e){//将mousemove函数提到全局
                    var e=e||event;//解决事件兼容问题,这里指的是鼠标事件
                    tuo.style.left=e.clientX-pos.x+"px";//div元素在页面的位置
                    tuo.style.top=e.clientY-pos.y+"px";
                    post.push({//将这些位置记录下来,放到post数组中
                        left:tuo.style.left,
                        top:tuo.style.top
                    });
                }
            tuo.addEventListener("mousedown",function(e){//鼠标左键按下事件
                var e=e||event;

                 pos={
                    x:e.offsetX,
                    y:e.offsetY
                };
                document.addEventListener("mousemove",move)//鼠标移动事件
            })
            document.addEventListener("mouseup",function(){//鼠标松开事件
                document.removeEventListener("mousemove",move)//清除鼠标移动事件
            })
            review.addEventListener("click",function(){//点击回放
                var timer=setInterval(function(){//执行一个定时器函数
                     current=post.pop();
                    while(!current){//当记录移动位置的数组不存在时,结束定时器
                        clearInterval(timer);
                        return;
                    }
                    tuo.style.left=current.left;//div元素在页面的位置
                    tuo.style.top=current.top;
                },50)//定时器50ms执行一次
            })
        }

    </script>
    <body>
        <div class="review">回放</div>
        <div class="tuo"></div>
    </body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_43031907/article/details/81915629