• JavaScript中的拖拽事件


    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>拖拽</title>
        <style>
            div{
                 100px;
                height: 100px;
                background-color: brown;
                position: absolute;
            }
            #box1{
                 100px;
                height: 100px;
                position: absolute;
                left: 200px;
                background-color:skyblue;
            }
            img{
                 100px;
                height: 100px;
                position: absolute;
                left: 400px;
            }
        </style>
        <script>
            window.onload = function () {
                var box = document.querySelector("#box");
                var box1 = document.querySelector("#box1");
                var img = document.querySelector("#img");
                drag(box);
                drag(box1);
                drag(img);
                // 将拖拽功能封装成了一个函数
                function drag(obj) {
                    obj.onmousedown = function (event) {
                        // 兼容IE8 调用IE特有的方法setCapture()
                        obj.setCapture && obj.setCapture();
                        event = event || window.event;
                        // 得到盒子和鼠标之间的相对位移
                        var ol = event.clientX - obj.offsetLeft;
                        var ot = event.clientY - obj.offsetTop;
    
                        document.onmousemove = function (event) {
                            event = event || window.event;
                            // 更改盒子的偏移量, 并减去盒子和鼠标的相对位移
                            obj.style.left = event.clientX - ol + "px";
                            obj.style.top = event.clientY - ot + "px";
                            // 兼容IE8 调用IE特有的方法releaseCapture()
                            obj.releaseCapture && obj.releaseCapture();
                        };
    
                        document.onmouseup = function () {
    
                            // 结束事件onmousemove  onmouseup
                            document.onmousemove = null;
                            document.onmouseup = null;
                        };
                        return false;
                    };
                }
            };
    
        </script>
    </head>
    <body>
    <div id="box"></div>
    <div id="box1"></div>
    <img src="../../images/headPortrait.jpg" id="img">
    </body>
    </html>
    

    在这里插入图片描述

  • 相关阅读:
    oraclesqlloader
    Dosinternal command and external command
    unixexpr
    Powerbuilder 6.5完全图解教程
    character set
    pbdatawindow function
    java decompile tool(recommended)
    php验证码背景色设置无效
    使用jquery validation engine判断为空的时候要根据input的type
    有些站点不能被iframe
  • 原文地址:https://www.cnblogs.com/TomHe789/p/12695904.html
Copyright © 2020-2023  润新知