zoukankan      html  css  js  c++  java
  • 关于移动div的具体实现(js)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>移动框练习</title>
        <style type = "text/css">
            #big{width: 300px;height: 200px;position: absolute;top: 200px;left: 300px;background: #ccc;}
            h1{width: 200px;height: 50px;line-height: 50px;text-align: center;background: orange;margin: 0 auto; cursor: move;}
        </style>
    </head>
    <body>
        <div id="big">
            <h1 class="titl"></h1>
        </div>
        <script type="text/javascript">
            //通过父元素获取到指定想要获取的元素。
            function getClass(clsName,parent){
                var oParent = parent?document.getElementById(parent):document;
                var oH1 = oParent.getElementsByClassName(clsName)[0];
                return oH1;
            }
            window.onload = drag;
            //给h1添加按住的事件。
            function drag(){
                var h1Node = getClass("titl","big");
                h1Node.onmousedown = fnDown;
            }
            //通过函数来获取指针的位置。
            function fnDown(event) {
                event = event || window.event;
                var oDiv = document.getElementById("big"),
                    //光标按下时光标和面板之间的距离。
                    disX = event.clientX-oDiv.offsetLeft;
                    disY = event.clientY-oDiv.offsetTop;
                document.onmousemove = function(event) {
                    event = event || window.event;
                    fnMove(event,disX,disY);
                }
                document.onmouseup = function(){
                    document.onmousemove = null;
                }
            }
            function fnMove(e,posX,posY) {
                var oDiv = document.getElementById("big"),
                    l = e.clientX-posX,
                    t = e.clientY-posY,
                    winW = document.documentElement.clientWidth || document.body.clientWidth,
                    winH = document.documentElement.clientHeight || document.body.clientHeight,
                    maxW = winW-oDiv.offsetWidth,
                    maxH = winH-oDiv.offsetHeight;
                if (l<0) {
                    l=10;
                } else if(l>maxW){
                    l=maxW;
                }
                if (t<0) {
                    t=10;
                } else if(t>maxH){
                    t=maxH;
                }
                oDiv.style.left = l+"px";
                oDiv.style.top = t+"px";
            }
        </script>
    </body>
    </html>
  • 相关阅读:
    php与nginx配置,不能运行php程序
    奇葩php之数组
    奇葩之mysql
    for语法研究
    php short tag不显示排查
    奇葩之mysql【三】我只想获得一个自增Id,我容易吗我
    男女不同
    Restart explorer
    iOS面试贴士
    phpmyadmin万能登陆密码
  • 原文地址:https://www.cnblogs.com/Arther-J/p/5396549.html
Copyright © 2011-2022 走看看