面向对象-拖拽

面向对象-拖拽

首次写面向对象的项目,我们先按照面向过程的思路写然后分割整理
面向过程把链条性的东西,拆分开来,写成一块一块的拿过来用

<!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>拖拽</title>
    <style>
        .box{
            width: 100px;
            height: 100px;
            position: relative;
            background-color: burlywood;
        }
    
    
    </style>
</head>
<body>

    <div class="box" style="left: 100px; top: 100px;"></div>
    <script>
        { 
            box = document.querySelector(".box");
            // let move;
            // 获取和设置 元素移动的值
            function css(el,attr,value){ //元素  什么属性移动 移动的值是多少                    
                // 这里有传三个参数 跟两个参数的问题  如果不传值就返回一个指定元素的指定属性
                // 如果传两参数 
                // 获取元素的值
                if(value === undefined){
                return parseInt(getComputedStyle(el[attr]))
                }
                //设置元素
                el.style[attr] = value + "px"
            }

            
            //按下
            box.addEventListener("mousedown",(ev)=>{
                //鼠标开始按下的位置
                starMove = {
                    x:ev.clientX,
                    y:ev.clientY,
                }
                //元素的位置
                boxMove = {
                    x:box.offsetLeft,
                    y:box.offsetTop,
                }
            //移动
            document.addEventListener("mousemove",move=(ev)=>{
                //鼠标移动后按下的新位置
                starEnd = {
                    x:ev.clientX,
                    y:ev.clientY,
                }
                //鼠标移动的距离
                starNew = {
                    x:starEnd.x - starMove.x,
                    y:starEnd.y - starMove.y,
                }
                
                //元素移动后的距离
                // box.style.left = (starNew.x + boxMove.x) + "px"
                // box.style.top = (starNew.y + boxMove.y) + "px"

                css(box,"left",starNew.x + boxMove.x)
                css(box,"top",starNew.y + boxMove.y)

            })//移动    
            //抬起 
            document.addEventListener("mouseup",()=>{
                document.removeEventListener("mousemove",move)
            })

            }) //按下

        }//块级作用域
    </script>
</body>
</html>
发布了96 篇原创文章 · 获赞 26 · 访问量 7270

猜你喜欢

转载自blog.csdn.net/weixin_46146313/article/details/104228155