关于移动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>

 

转载于:https://www.cnblogs.com/Arther-J/p/5396549.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值