日常开发小汇总(6)元素跟随鼠标移动(在视口下移动)

日常开发小汇总(6)元素跟随鼠标移动(在视口下移动)_第1张图片

<div class="mark">
        <h1>titleh1>
        <div>
           <p>title 鼠标移动 盒子整体移动p>
           <p>testp>
           <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Modi, porro.p>
        div>

    div>
 const mark = document.querySelector(".mark")
        const title = document.querySelector("h1")
        title.onmousedown = function(e){
            //鼠标按下时,鼠标起始位置
            let x = e.clientX;
            let y = e.clientY;
            let markrect = mark.getBoundingClientRect();
            console.log(markrect)

            //获取视口的宽高
            let clientW = document.documentElement.clientWidth;
            let clientH = document.documentElement.clientHeight;
            //获取mark元素的宽高
            let markW = mark.offsetWidth;
            let markH = mark.offsetHeight;
            //获取水平\垂直移动位置的最大值
            let maxLeft = clientW - markW;
            let maxTop = clientH - markH;
            console.log(markW,markH)
            console.log(maxLeft,maxTop)
            window.onmousemove = function(e){
                //鼠标起始位与移动后位置之间的距离
                let disX = e.clientX - x;
                let disY = e.clientY - y;
                //元素的原始位置+ 鼠标移动距离 即 元素的现在位置
                let left = markrect.left + disX;
                let top = markrect.top + disY
                if(left < 0){
                    left = 0;
                }else if(left >maxLeft){
                    left = maxLeft
                }
                 if(top < 0){
                    top = 0;
                }else if(top >maxTop){
                    top = maxTop
                }
                mark.style.top =  top + "px";
                mark.style.left =  left + "px";

            }
            window.onmouseup = function(){
                console.log("up")
                window.onmousemove = null;
                window.onmouseup = null;
            }
        }

你可能感兴趣的:(计算机外设,javascript,前端)