美文网首页
案例:鼠标拖拽

案例:鼠标拖拽

作者: kino2046 | 来源:发表于2019-10-31 13:04 被阅读0次

    <!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 {

        position: absolute;

        left: 0;

        top: 0;

        width: 100px;

        height: 100px;

        background: red;

    }

    </style>

    </head>

    <body>

    文字 <br />

    文字 <br />

    文字 <br />

    文字 <br />

    文字 <br />

    文字 <br />

    文字 <br />

    <div class="box">文字</div>   

    <script src="fns.js"></script> 

    <script>

    {

        // 拖拽

        let box = document.querySelector(".box");

        // 鼠标按下事件

        let startMouse = {};

        let startEl = {};

        // 鼠标移动

        let move = (e)=>{

            let nowMouse = {

                x: e.clientX,

                y: e.clientY

            };

            let disMouse = {

                x: nowMouse.x - startMouse.x,

                y: nowMouse.y - startMouse.y

            };

           css(box,"left",startEl.x + disMouse.x);

           css(box,"top",startEl.y + disMouse.y);

        };

        box.addEventListener("mousedown",(e)=>{

            startMouse = {

                x: e.clientX,

                y: e.clientY

            };

            startEl = {

                x: css(box,"left"),

                y: css(box,"top")

            }

            document.addEventListener("mousemove",move);

            document.addEventListener("mouseup",()=>{

                document.removeEventListener("mousemove",move);

            },{

                once: true

            });

            e.preventDefault();

        });

    }

    </script>

    </body>

    </html>

    相关文章

      网友评论

          本文标题:案例:鼠标拖拽

          本文链接:https://www.haomeiwen.com/subject/mxttbctx.html