其他分享
首页 > 其他分享> > 点击拖动div

点击拖动div

作者:互联网

JS

<script>
        const wrapper = document.querySelector(".wrapper")
        header = wrapper.querySelector('header')
        function onDrag({movementX,movementY}){
            // window.getComputedStyle() 获取样式 接收两个参数 第一个参数是要获取的元素
            let getStyle = window.getComputedStyle(wrapper)
            let left =parseInt(getStyle.left) 
            let top =parseInt(getStyle.top) 
            // movementX与movementY 表示鼠标移动的值
            wrapper.style.top = `${top + movementY}px`
            wrapper.style.left = `${left +movementX}px`
        }

        header.addEventListener("mousedown",(e)=>{
            header.classList.add("active")
            header.addEventListener("mousemove",onDrag )
        })

        document.addEventListener("mouseup",()=>{
            header.classList.remove("active")
            header.removeEventListener("mousemove",onDrag)
        })
    </script>

  

CSS

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;

}

body {
    background: #6f36ff;
}

.wrapper {
    background-color: #fff;
    width: 450px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%) scale(1.4);
    border-radius: 10px;
}

.wrapper header{
    font-size: 23px;
    font-weight: 500;
    color: #6f36ff;
    padding: 17px 30px;
    border-bottom: 1px solid #6f36ff;
}

.wrapper .content {
    margin: 30px 30px 40px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.content .icon {
    height: 95px;
    width: 95px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 50%;
    border:5px solid #6f36ff ;
    font-size: 60px;
    color: #6f36ff;
}

.content .title
 {
    font-size: 29px;
    font-weight: 500;
    margin: 15px 0;
 }

 .content p {
    font-size: 16px;
    text-align: center;
 }

 .wrapper header.active {
    cursor: move;
    user-select: none;
 }

  

 

HTML

 <div class="wrapper">
        <header>拖动 DIV</header>
        <div class="content">
            <div class="icon">+</div>
            <div class="title">拖动 DIV</div>
            <p>鼠标按下拖动,放开结束</p>
        </div>
    </div>

标签:拖动,top,wrapper,content,header,点击,6f36ff,div,font
来源: https://www.cnblogs.com/hoodoo/p/16591995.html