欢迎光临散文网 会员登陆 & 注册

WEB前端实例,JS实现拖拽效果~

2023-01-31 10:26 作者:听听浪浪山  | 我要投稿

<!-- <!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

    <style>

            div{

                width: 200px;

                height: 200px;

                background-color: red;

                border-radius: 15px;

                box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.7);

                position: absolute;

                top: 300px;

                left: 1000px;

            }

    </style>

</head>

<body>

    <div></div>

    <script>

        let oDiv = document.querySelector('div');

        let flag = false;

        oDiv.addEventListener('mousedown',(e) => {

            flag = true;

            let x = e.offsetX;

            let y = e.offsetY;

            document.addEventListener('mousemove',(e) => {

                let _h = window.innerHeight - oDiv.offsetHeight;

                let _w = window.innerWidth - oDiv.offsetWidth;


                let div_left = e.clientX -x;

                let div_top = e.clientY - y;


                div_top = Math.min(Math.max(0,div_top),_h);

                div_left = Math.min(Math.max(0,div_left),_w);


                if(flag){

                    oDiv.style.top = div_top + 'px';

                    oDiv.style.left = div_left + 'px';

                }


            });

        });


        oDiv.addEventListener('mouseup',(e) => {

            flag = false;

        });

    </script>

</body>

</html> -->

WEB前端实例,JS实现拖拽效果~的评论 (共 条)

分享到微博请遵守国家法律