欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

让div在body中任意拖动

程序员文章站 2022-10-05 19:26:29
HTML代码 CSS代码 JS代码 ......

html代码

<div id="idouterdiv" class="csouterdiv">
 
</div>

css代码

body {
    background-color:#232429;
}
.csouterdiv {
    width:256px;
    height:146px;
    background-color:white;
    position:absolute;
    top:50%;
    left:50%;
    transform:translatex(-50%) translatey(-50%);
    -moz-transform:translatex(-50%) translatey(-50%);
    -webkit-transform:translatex(-50%) translatey(-50%);
    -ms-transform:translatex(-50%) translatey(-50%);
    border-radius:5px;
    box-shadow:3px 3px  10px blue;
}

js代码

function dragfunc(id) {
    var drag = document.getelementbyid(id);
    drag.onmousedown = function(event) {
        var ev = event || window.event;
        event.stoppropagation();
        var disx = ev.clientx - drag.offsetleft;
        var disy = ev.clienty - drag.offsettop;
        document.onmousemove = function(event) {
            var ev = event || window.event;
            drag.style.left = ev.clientx - disx + "px";
            drag.style.top = ev.clienty - disy + "px";
            drag.style.cursor = "move";
        };
    };
    drag.onmouseup = function() {
        document.onmousemove = null;
        this.style.cursor = "default";
    };
};
dragfunc("idouterdiv");