zoukankan      html  css  js  c++  java
  • 实现一个简单拖拽

    <!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>
    </head>
    <body>
        <div id="box"></div>
    </body>
    </html>
    <script>
        window.onload = function () {
            var box = document.getElementById('box');
            box.onmousedown = function (ev) {
                var oEvent = ev || window.event; // 兼容火狐,火狐下没有window.event
                var distanceX = oEvent.clientX - box.offsetLeft; // 鼠标到可视区左边的距离 - box到页面左边的距离
                var distanceY = oEvent.clientY - box.offsetTop;
                document.onmousemove = function (ev) {
                var oEvent = ev || window.event;
                var left = oEvent.clientX - distanceX;
                var top = oEvent.clientY - distanceY;
                if (left <= 0) {
                    left = 0;
                } else if (left >= document.documentElement.clientWidth - box.offsetWidth) {
                    left = document.documentElement.clientWidth - box.offsetWidth;
                }
                if (top <= 0) {
                    top = 0;
                } else if (top >= document.documentElement.clientHeight - box.offsetHeight) {
                    top = document.documentElement.clientHeight - box.offsetHeight;
                }
                box.style.left = left + 'px';
                box.style.top = top + 'px';
                }
                box.onmouseup = function () {
                document.onmousemove = null;
                box.onmouseup = null;
                }
            }
        }
    </script>
    <style>
        html, body {
            margin: 0;
            height: 100%;
        }
        #box {
             100px;
            height: 100px;
            background-color: red;
            position: absolute;
            top: 100px;
            left: 100px;
        }
    </style>
  • 相关阅读:
    基本数据类型(int, bool, str)
    万恶之源之运算符
    python基础初识
    leetcode 653. Two Sum IV
    leetcode 16 3Sum Closest
    leetcode15 3Sum
    leetcode 1 Two Sum
    【站立会议】第四天
    【站立会议】第三天
    【站立会议】第二天
  • 原文地址:https://www.cnblogs.com/xiaohuohuai/p/15165202.html
Copyright © 2011-2022 走看看