div free drag (pc)

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>js--div自由拖动(在body可以自由拖动)</title>
<style>
.mydiv {
position:fixed;
width:400px;
height:400px;
background-color:blue;
filter:Alpha(opacity=50);
opacity:0.5;
}
</style>
</head>
<body>
<div id="drag" class="mydiv" style="left:0px;top: 20px;"></div>
<script>
var posX;
var posY;
fdrag = document.getElementById("drag");
fdrag.onmousedown = function(e) {
    posX = event.x - fdrag.offsetLeft; //Get the abscissa x
    posY = event.y - fdrag.offsetTop; //Get the ordinate y
    document.onmousemove = mousemove; //Call the function, as long as you keep pressing the button, you can keep calling
}
document.onmouseup = function() {
    document.onmousemove = null; //Mouse up, stop
}
function mousemove(ev) {
    if (ev == null) ev = window.event; //IE
    fdrag.style.left = (ev.clientX - posX) + "px";
    fdrag.style.top = (ev.clientY - posY) + "px" ;
}
</script>
</body>
</html>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324820759&siteId=291194637