短视频程序源码,实现选中可拖拽功能

2020-09-27 17:46:59 浏览数 (1)

代码语言:javascript复制

在这里插入代码片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>div{width: 100px;height: 100px;border-radius: 50px;background: red;position: absolute;}</style>
</head>
<body>
    <div></div>
    <script>
        var oDiv = document.querySelector("div");//首先获取要拖拽的div
        //获取当前可视界面的宽高
        var cw =document.documentElement.clientWidth;
        var ch =document.documentElement.clientHeight;
        //获取div的宽高
        var dt =oDiv.clientWidth;
        var dh =oDiv.clientHeight;
        //添加鼠标落下事件
        oDiv.onmousedown = function(e){
            var evt = e||event;
            //获取事件对象距离事件源的距离
            var x = evt.offsetX;
            var y = evt.offsetY;
            //验证
            console.log(x);
            console.log(y);
            //添加鼠标移动事件
            document.onmousemove =function(e){
                var evt = e||event;
    //算出div移动时距离可视界面的事实距离
                var i=evt.clientX-x;
                var j=evt.clientY-y;
    //限制出界
                i=i<=0?0:i>=cw-dt?cw-dt:i;
                j=j<=0?0:j>=ch-dh?ct-dh:j;
    //
                oDiv.style.left = i "px";
                oDiv.style.top =j "px";
            }
            //
            document.οnmοuseup=function(){
  //清除
                document.οnmοusemοve=null;
            }
        }
    </script>
</body>
</html>
# 标题

0 人点赞