div自由拖动(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; //获得横坐标x
    posY = event.y - fdrag.offsetTop; //获得纵坐标y
    document.onmousemove = mousemove; //调用函数,只要一直按着按钮就能一直调用
}
document.onmouseup = function() {
    document.onmousemove = null; //鼠标举起,停止
}
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>

猜你喜欢

转载自blog.csdn.net/qq_38881495/article/details/80069258
今日推荐