zoukankan      html  css  js  c++  java
  • JS实现 div拖拽 限制在屏幕内

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <style>
    #div1 {width:100px; height:100px; background:red; position:absolute;}
    div {width:3px; height:3px; position:absolute; background:black;}
    </style>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文档</title>
    <script>
    window.onload=function ()
    {
        var oDiv=document.getElementById('div1');
        
        oDiv.onmousedown=function (ev)
        {
            var oEvent=ev||event;
            
            var disX=oEvent.clientX-oDiv.offsetLeft;
            var disY=oEvent.clientY-oDiv.offsetTop;
            
            document.onmousemove=function (ev)
            {
                var oEvent=ev||event;
                
                var l=oEvent.clientX-disX;
                var t=oEvent.clientY-disY;
                
                if(l <=0 ){
                    oDiv.style.left = 0
                }else if(oEvent.clientX >= document.body.clientWidth){
                    oDiv.style.left = oEvent.clientX - oDiv.offsetWidth + 'px'
                }else{
                    oDiv.style.left=l+'px';
                }
                if(t <=0 ){
                    oDiv.style.top = 0
                }else if(oEvent.clientY >= document.body.clientHeight){
                    oDiv.style.top = oEvent.clientY - oDiv.offsetHeight + 'px'
                }else{
                    oDiv.style.top=t+'px';
                }
            };
            
            document.onmouseup=function ()
            {
                document.onmousemove=null;
                document.onmouseup=null;
            };
        };
    };
    
    </script>
    </head>
    
    <body>
    <div id="div1">
    </div>
    </body>
    </html>
  • 相关阅读:
    ZeroMQ自查手册
    如何回答——请简述MySQL索引类型
    101. 对称二叉树
    66. 加一
    104. 二叉树的最大深度
    724.寻找数组的中心索引
    33. 搜索旋转排序数组
    快速排序
    Vue
    HTML
  • 原文地址:https://www.cnblogs.com/tabCtrlShift/p/6282619.html
Copyright © 2011-2022 走看看