html5,js实践拖曳效果

<!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>
        * {
            margin: 0px;
            height: 0px;
            box-sizing: border-box;

        }

        #box {
            position: absolute;
            background-color: #d38383;
            width: 200px;
            height: 200px;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div id="box"></div>
    <script>
        let box = document.getElementById("box")
        box.onmousedown = function (d) {
            let offsetX = d.offsetX
            let offsetY = d.offsetY
            document.onmousemove = function (e) {
                console.log(e)
                let _left = e.clientX
                let _top = e.clientY
                top1 = _top - offsetY
                left2 = _left - offsetX
                if (top1 < 1) {
                    top1 = 0
                }
                if (left2 < 0) {
                    left2 = 0
                }
                if (left2 > 1585 - offsetX)
                 { 
                    left2 = 1585-offsetX
                 }
                 if(top1>970-offsetY)
                 {
                    top1=970-offsetY
                 }
                box.style.left = left2 + 'px'
                box.style.top = top1 + 'px'
            }
            document.onmouseup = function () {
                document.onmousemove = null

            }
        }

    </script>
</body>

</html>

实践总结:该代码考验了js的运用;其中用clientx,clienty,来找出鼠标到浏览器的距离;用offsetx,offsety,来找出鼠标在div中的距离;通过clientx-offsetx;clienty-offsety来确定div在浏览器中的位置,用function(e)和console.log来查找数值防止div超出网页;并学习了一个新效果

class+.style+.css类型="效果名称"代码中给出的是box.style.left=left2+'px'和position:absolute;以网页为父标签的绝对定位来实时确定div在网页中的位置;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值