<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
body{
height: 1000px;
}
div{
width: 100px;
height: 100px;
position: absolute;
background: #FF0000;
}
</style>
</head>
<body>
<div>
</div>
<script type="text/javascript">
var oDiv = document.querySelectorAll("div")[0];
var cw = document.documentElement.clientWidth;
var ch = document.documentElement.clientHeight;
var dw = oDiv.offsetWidth;
var dh = oDiv.offsetHeight;
var mw = cw-dw;
var mh = ch-dh;
oDiv.onmousedown = function(e){
var evt = e || event;
var _x = evt.offsetX;
var _y = evt.offsetY;
document.onmousemove = function(e){
var evt = e || event;
var x = evt.clientX-_x;
var y = evt.clientY-_y;
if(x<0){
x = 0;
}
if(x>mw){
x = mw;
}
if(y<0){
y = 0;
}
if(y>mh){
y = mh;
}
oDiv.style.left = x + "px";
oDiv.style.top = y + "px";
}
document.onmouseup = function(){
document.onmousemove = null;
}
}
</script>
</body>
</html>
js 简单拖拽
最新推荐文章于 2022-10-06 10:36:23 发布