点击拖动div

JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
*{
    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

1
2
3
4
5
6
7
8
<div class="wrapper">
       <header>拖动 DIV</header>
       <div class="content">
           <div class="icon">+</div>
           <div class="title">拖动 DIV</div>
           <p>鼠标按下拖动,放开结束</p>
       </div>
   </div>
posted @   指尖掠过  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示