javascript - 目标:实现一个子div只能在父div中拖动
天蓬老师
天蓬老师 2017-04-11 11:39:49
[JavaScript讨论组]

要求实现一个子p只能在父p中拖动,现效果已实现,可是有个问题是当我将mousemove和mouseup绑定在child上时,只能实现一次拖拽,而将其绑定在document上时,便可实现随意拖拽。为什么绑定在child上就只能拖拽一次呢?代码如下:


<head lang="en">
    <meta charset="UTF-8">
    <title>父元素内拖拽</title>
</head>
<style>
    #parent{
        width: 300px;
        height: 300px;
        background-color:lightskyblue;
        position: relative;
    }
    #child{
        width: 100px;
        height: 100px;
        background-color:hotpink;
        position: absolute;
        cursor: pointer;
    }
</style>
<body>
<p id ="parent">
    <p id ="child"></p>
</p>
</body>
window.onload = function(event){

    var parent = document.getElementById("parent");
    var child  = document.getElementById("child");
    var  disX  = 0; //鼠标按下时相对父元素的距离
    var  disY  = 0;

   child.onmousedown = function(event){
      var event = event||window.event;
      disX = event.clientX - child.offsetLeft;
      disY = event.clientY - child.offsetTop;

        document.onmousemove = function(event){
            var event =event||window.event;
            var l = event.clientX - disX;
            var t = event.clientY - disY;
            if(l < 0){
                l = 0;
            }else if(l > parent.offsetWidth - child.offsetWidth){
                l = parent.offsetWidth - child.offsetWidth;
            }
            if(t < 0){
                t = 0;
            }else if(t > parent.offsetHeight - child.offsetHeight){
                t = parent.offsetHeight - child.offsetHeight;
            }
            //css定位
            child.style.left = l +'px';
            child.style.top =t + 'px';
        };
       document.onmouseup = function(event){
            document.onmousedown = null;
            document.onmousemove = null;
        };
    };
}
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回复(1)
迷茫
    document.onmouseup = function(event){
        document.onmousedown = null;
        document.onmousemove = null;
    };改为绑定在child上是这样吗?
    child.onmouseup = function(event){
        child.onmousedown = null;//鼠标按下的事件已经被你清楚,所以只有一次
        child.onmousemove = null;
    };
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号