JS C22作业:方块拖拽效果

 

 

(1)鼠标移动

    document.onmousemove = function(e){
        var event = e || window.event;
        console.log(e.pageX + " " + e.pageY)             //代表鼠标点击位置,MouseEvent里面包含该属性
    }

(2)把移动的点绑定在div里面就能实现拖拽了

    <style>
        .wrapper{
            width: 30px;
            height:30px;
            background-color: aqua;
            position: absolute;
            left:0;
            top:0;                   //只要用到这两个属性就要取0;否则默认就会有auto值
        }
    </style>
    <link href="style1.css" rel="stylesheet">
</head>
<body>​
<div class="wrapper"> </div>​


    var div = document.getElementsByTagName('div')[0];
    div.onmousedown = function(e) {
        event = e || window.event;

        document.onmousemove = function(e){              // document改为div也行,但是会出现鼠标跟丢的现象,document就不会
            event = e || window.event;
            div.style.left = event.pageX -15 + "px";     // 减去长宽的一半,保证点击位置时刻在中央
            div.style.top = event.pageY -15 + "px";
        }
        div.onmouseup = function () {
            document.onmousemove = null;
        }
    }

 

div.setCapture();        IE里面的事件捕获:会把当前所有事件都绑定在div上面

div.releaseCapture();  这两个知道就好,不用操作

 

封装起来的样子:没写部分不懂

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值