LOADING

jQuery实现拖拽元素

–>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style>
            div {
                width: 200px;
                height: 200px;
                background-color: red;
                position: absolute;
                cursor: move;
            }

            * {
                margin: 0;
                padding: 0;
            }
        </style>
    </head>
    <body>
        <div>dsgsad</div>
        <div>dsgsad</div>
        <div>dsgsad</div>
        <div>dsgsad</div>
    </body>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $('div').on('mousedown', function(e) { //鼠标按下
            $(document).on('mousemove', (e) => {//鼠标移动
                let left = e.clientX - $(this).width() / 2//计算元素left值
                let top = e.clientY - $(this).height() / 2//计算元素top值
                top = suan(top, 0, $(document).innerHeight() - $(this).height())//调用封装的方法
                left = suan(left, 0,$(document).innerWidth() - $(this).width())//调用封装的方法
                $(this).css({ //给盒子设置坐标
                    left,
                    top
                })
                e.preventDefault();
            })
            $(document).on('mouseup', (e) => {//鼠标抬起
                $(document).off('mousemove')//移除鼠标移动事件
            })
        })
        function suan(o, min, max) { //重复封装
            o < min ? o = min : o > max ? o = max : ''//限制出界
            return o
        }
    </script>
</html>

 

原文链接:https://www.cnblogs.com/zlf1914/p/13086444.html
本文来源 互联网收集,文章内容系作者个人观点,不代表 本站 对观点赞同或支持。如需转载,请注明文章来源,如您发现有涉嫌抄袭侵权的内容,请联系本站核实处理。

© 版权声明

相关文章