拖拽效果js

本文介绍了如何使用JavaScript实现网页元素的拖拽功能,包括设置拖拽起点、监听鼠标移动事件、更新元素位置等关键步骤。通过结合HTML和CSS,你可以创建交互性强的拖放用户体验。
摘要由CSDN通过智能技术生成
<!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: 0;
            padding: 0;
        }
    </style>
</head>

<body>
    <div style="width: 100px;height: 100px;background-color: red;border: 1px solid black;position: relative;">

    </div>
    <script>
        var box = document.querySelector('div'),
            broswerWidth = document.body.clientWidth,
            broswerHeight = document.documentElement.clientHeight;

        document.onmousedown = function (e) {
            to_left = e.clientX - box.offsetLeft;
            to_top = e.clientY - box.offsetTop
            key = true;
            box.style.cursor = 'move'
        document.onmousemove = function (e) {
            if (key == false) {  return}
            nx = e.clientX      ;ny = e.clientY
            box.style.left = nx - to_left + 'px'
            box.style.top = ny - to_top + 'px'
            //盒子移动后位置=鼠标位置-鼠标相对于盒子的距离
            if (box.offsetLeft < 0) {//if判断必须在box.style.left/top下面
                box.style.left = 0}
            if (box.offsetTop < 0) {
                box.style.top = 0}
            if (box.offsetLeft + box.clientWidth > broswerWidth) {
                box.style.left = broswerWidth - box.clientWidth + 'px'}
            if (box.offsetTop + box.clientHeight > broswerHeight) {
                box.style.top = broswerHeight - box.clientHeight + 'px' } }
        document.onmouseup = function () {  //box也可
            key = false;
            box.style.cursor = 'defalt' }
        }
    </script>
</body>

</html>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值