<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{margin: 0px; padding: 0px;}
p {
width: 200px;
height: 200px;
background: green;
position: absolute;
cursor: move;
}
</style>
</head>
<body>
<p></p>
</body>
<script type="text/javascript">
var p = document.querySelector('p');
var pWidth = p.offsetWidth;
var pHeight = p.offsetHeight;
var maxWidth = document.documentElement.clientWidth - pWidth;
var maxHeight = document.documentElement.clientHeight - pHeight;
p.onmousedown = function(e){
var pLeft = p.offsetLeft;
var pTop = p.offsetTop;
var eLeft = e.clientX;
var eTop = e.clientY;
var _x = eLeft - pLeft;
var _y = eTop - pTop;
document.documentElement.onmousemove = function(ev){
console.log(111);
var evLeft = ev.clientX;
var evTop = ev.clientY;
var x = evLeft - _x;
var y = evTop - _y;
if(x>=maxWidth){
x = maxWidth;
}
if(x<0){
x = 0;
}
if(y>=maxHeight){
y = maxHeight;
}
if(y<0){
y = 0;
}
p.style.left = x+'px';
p.style.top = y+'px';
}
}
document.documentElement.onmouseup = function(){
document.documentElement.onmousemove = null;
}
</script>
</html>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
你是在document上对p进行移动的呀,当然委托给document来获取鼠标的坐标值最为方便最为准确了。
谁说一定呀!!!
不是一定的绑在p也可以