盒子拖拽效果,原生js实现

1 篇文章 0 订阅

原生js实现拖拽效果

<!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>hello2</title>
    
</head>
<style>
    #box1{
    position: absolute;
    width: 100px;
    height: 100px;
    background: blue;
    cursor: move;
    }
</style>
<body>
   
     <div id="box1">
   
     </div>   
    
</body>
</html>
<script type="text/javaScript">
    //     拖拽box1元素
    // 拖拽的流程
    // 1.当鼠标在被拖拽元素上按下时,开始拖拽 onmousedown
    // 2。当鼠标移动时被拖拽元素跟随鼠标移动 onmousemove
    // 3。当鼠标松开时,被拖拽元素固定在当前位置 onmouseup
    window.onload = function(){
        
        //获取box1
        var box1 = document.getElementById("box1");
        //为box1绑定一个鼠标按下事件/
        //当鼠标在被拖拽元素上按下时,开始拖拽 onmousedown
        box1.onmousedown = function(event){
        
            //设置box1捕获所有鼠标按下的事件
            // if(box1.setCapture){
            //     box1.setCapture();
            // }
            // box1.setCapture && box1.setCapture();
             var event = event || window.event;
            //div的偏移量 鼠标clentX- 元素.offsetLeft
            //div的偏移量 鼠标.clentY - 元素.offsetTop
            var ol = event.clientX - box1.offsetLeft;
            var ot = event.clientY - box1.offsetTop;
            
            //为document绑定一个onmousemove事件
            document.onmousemove = function(event){
                var event = event  || window.event;
                //当鼠标移动时被拖拽元素跟随鼠标移动 onmousemove
                //获取鼠标的坐标
                var left = event.clientX -ol;
                var top = event.clientY- ot;
                //修改box1的位置
                box1.style.left = left+"px";
                box1.style.top = top+"px";
                
            };
            //为元素绑定一个鼠标松开事件
            document.onmouseup = function(event){
                //当鼠标松开时,被拖拽元素固定在当前位置 onmouseup
                //取消document的onmousemove事件
                this.onmousemove = null;
                //取消document的onmouseup事件
                this.onmouseup = null;
                console.log("nihao");
                //当鼠标松开时,取消对事件的捕获
                // box1.releaseCapture();
                // box1.releasePointerCapture && box1.releasePointerCapture();
            };
            //当我们拖拽一个网页中的内容时,浏览器会默认去搜索引擎中搜索内容此时会导致拖拽功能的异常,这个是浏览器提供的默认行为,如果不希望发生这个行为,则可以通过return false来取消默认行为
            //不这对IE8不起作用
            return false;
        };
    };
    
</script>

效果图

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值