• 原生js拖拽


    <!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">
        <meta name="author" content="杨欣">
        <title>原生js拖拽</title>
        <style>
            div {
                 200px;
                height: 200px;
                background: red;
                position: absolute;
            }
        </style>
    </head>
    
    <body>
    
        <div id="div"></div>
    
        <script>
            //获取元素
            var div = document.getElementById('div');
            var x = 0;
            var y = 0;
            var l = 0;
            var t = 0;
            var isDown = false;
            //鼠标按下事件
            div.onmousedown = function (e) {
                //获取x坐标和y坐标
                x = e.clientX;
                y = e.clientY;
    
                //获取左部和顶部的偏移量
                l = div.offsetLeft;
                t = div.offsetTop;
                //开关打开
                isDown = true;
                //设置样式  
                div.style.cursor = 'move';
            }
            //鼠标移动
            window.onmousemove = function (e) {
                if (isDown == false) {
                    return;
                }
                //获取x和y
                var nx = e.clientX;
                var ny = e.clientY;
                //计算移动后的左偏移量和顶部的偏移量
                var nl = nx - (x - l);
                var nt = ny - (y - t);
    
                div.style.left = nl + 'px';
                div.style.top = nt + 'px';
            }
            //鼠标抬起事件
            div.onmouseup = function () {
                //开关关闭
                isDown = false;
                div.style.cursor = 'default';
            }
    
        </script>
    </body>
    
    </html>
    
  • 相关阅读:
    EOJ2032 判断两个数是否相等
    EOJ2529 强大的lwc
    EOJ 1199 Anagram
    EOJ2530 数字之和
    EOJ2941 在线投票系统
    EOJ2124 Seamild的电梯
    EOJ 1027 邮资的问题
    通过js导入js,通过js导入css
    无意间在我系统中发现的一张图~~~~~
    css系列看过之后让我~~~
  • 原文地址:https://www.cnblogs.com/samsara-yx/p/12573413.html
Copyright © 2020-2023  润新知