4.6、拖拽和IE事件的全局捕获和全局释放

一、案例


```go
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #box {
            width: 200px;
            height: 200px;
            background: red;
            position: absolute;
            text-align: center;
        }
        
        #box img {
            width: 100px;
            height: 100px;
            background: brown;
        }
    </style>
</head>

<body>
    <div id="box">
        哈哈哈哈
        <img src="./image/1.png" alt="">
    </div>
    <script>
        //鼠标事件
        // onmousedown 鼠标抬起
        // onmousemove 鼠标移动  在onmousedown 中定义
        // onmouseup 鼠标放下  在onmousedown 中定义
        var box = document.getElementById('box')
            //按下
        box.onmousedown = function(ev) {
            //兼容IE8及以下设置全局捕获,阻止默认行为
            if (box.setCapture) {
                box.setCapture()
            }

            var ev = ev || event
                //获取鼠标到盒子的距离=鼠标到文档的距离-盒子到文档的距离
            var clx = ev.clientX - box.offsetLeft
            var cly = ev.clientY - box.offsetTop
            console.log(clx, cly)
                //拖动
            document.onmousemove = function(ev) {
                    var ev = ev || event
                    box.style.left = ev.clientX - clx + 'px'
                    box.style.top = ev.clientY - cly + 'px'
                }
                //     //抬起
            box.onmouseup = function() {
                    // 鼠标按下的时候取消box绑定的事件
                    document.onmousemove = null; //这里应该改为document 移动的事件
                    document.onmouseup = null; //当这个元素
                    console.log('234567')
                }
                //阻止文字或是图片 进入浏览器搜索的默认行为  IE678 不支持
            return false
                //IE8及以下的取消全局捕获 
            if (box.releaseCapture) {
                box.releaseCapture()
            }
        }
    </script>
</body>

</html>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值