js实现元素拖拽

这里介绍两种实现元素拖拽的方法

<style>
     *{margin:0;padding:0}
     .box{position:absolute;
          top:0;
          left:0;
          width:300px;
          height:300px;
          background-color: chocolate;
     }
     </style>
     <body>
     <div class="box"></div>

先定义一个元素

方法1

 <script>
    let box=document.getElementsByClassName("box")[0];
    //鼠标按下事件
    box.onmousedown=function(e){//e为事件源
        let Top=box.offsetTop,//获取元素的top值
            Left=box.offsetLeft,//获取元素的left值
            X=e.clientX,//获取鼠标点击时的位置
            Y=e.clientY;//获取鼠标点击时的位置
            //鼠标移动事件
            document.onmousemove=function(e){
                box.style.top=e.clientY-Y+Top+"px";
                box.style.left=e.clientX-X+Left+"px"
            }
    }
    //鼠标松开事件
    document.onmouseup=function(){
        document.onmousemove=null;
    }

方法2

<div class"box" draggable="true"></div>           
 <script>
    let box=document.getElementsByClassName("box")[0];
    box.ondragend=function(e){
    box.style.cssText=`left:${e.clientX-0}px;top:${e.clientY-0}px;`
}
</script>

这是h5的拖拽。不过本人觉得原生js的用起来比较舒服,还有,此方法不兼容火狐,只能在谷歌下用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值