版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/boonyaxnn/article/details/89194302
一、html代码
<div class="max"> <div class="small"></div> </div>
二、css样式
<style> * { margin: 0; padding: 0; } .max { height: 400px; width: 400px; border: 2px solid skyblue; position: relative; left: 100px; top: 50px; } .small { height: 100px; position: absolute; left: 100px; top: 50px; width: 100px; background-color: orange; } </style>
三、js代码
<script> //1.获取界面元素 var max = document.querySelector('.max'); var small = document.querySelector('.small'); //判断鼠标是否在small上按下 var flag = false; //2.鼠标按下事件 small var delX = 0; var delY = 0; small.onmousedown = function () { flag = true; delX = event.clientX - small.offsetLeft; delY = event.clientY - small.offsetTop; console.log('delX',delX,'delY',delY); }; //3.鼠标移动事件 max max.onmousemove = function () { if (flag) { var x = event.clientX - delX; var y = event.clientY - delY; if(x<20){ x = 0; } if(y<20){ y = 0; } if(x>max.clientWidth - small.clientWidth -20){ x = 300; } if(y>max.clientHeight - small.clientHeight -20){ y = 300; } console.log('x',x,'y',y); small.style.left = x+'px'; small.style.top = y+'px'; } }; //4.鼠标抬起事件 document document.onmouseup = function () { flag = false; }; </script>