鼠标放上去拖拽2

<!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>
        * {
            padding: 0;
            margin: 0;
        }

        #box {
            width: 300px;
            height: 300px;
            background: lightgray;
            position: absolute;
        }

        #box2 {
            width: 100%;
            height: 50px;
            line-height: 50px;
            background: pink;
            text-align: center;
            font-size: 23px;
            user-select: none;
        }
    </style>
</head>

<body>
    <div id="box">
        <div id="box2">zhuzhuxia</div>
    </div>
    <script>
        let winW = document.documentElement.clientWidth,//整个屏幕的宽度
            winH = document.documentElement.clientHeight,//整个屏幕的高度
            box = document.getElementById('box');//盒子

        box.style.position = 'absolute';//给box相对定位----让盒子水平垂直居中
        box.style.left = (winW - 300) / 2 + 'px';//整个屏幕的宽度-自身宽度/2
        box.style.top = (winH - 300) / 2 + 'px';//整个屏幕的高度-自身高度/2

        /*  box.style.left = (winW - box.offsetWidth) / 2 + 'px';
            box.style.top = (winH - box.offsetHeight) / 2 + 'px'; */
        //

        function move(e) {//只要鼠标移动
            //获光标最新left值
            let clientX = e.clientX;
            let clientY = e.clientY;
          
            //给box设置最新的left和top即可---最新-旧的+left(起始)
            box.style.left = clientX - this.initClientX + this.initLeft + "px";
            box.style.top = clientY - this.initClientY + this.initTop + "px";


        }
        function up() {
            window.onmousemove = null;//出来不动
        }
        function down(e) {//在鼠标按下时候,会把当前起始的box的left值和光标的
            //clientX值保存
            this.initLeft = parseFloat(box.style.left);//把初始的left值保存到title身上
            this.initTop = parseFloat(box.style.top);
            this.initClientX = e.clientX;//初始值
            this.initClientY = e.clientY;

            window.onmousemove = move.bind(box2);//括号里写this也行
        }

        box2.onmousedown = down;
        window.onmouseup = up;
    </script>
</body>

</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值